Home » Php » What does the .= operator mean in PHP?

What does the .= operator mean in PHP?

Posted by: admin April 23, 2020 Leave a comment


I have a variable that is being defined as

$var .= "value";

How does the use of the dot equal function?

How to&Answers:

It’s the concatenating assignment operator. It works similarly to:

$var = $var . "value";

$x .= differs from $x = $x . in that the former is in-place, but the latter re-assigns $x.


This is for concatenation

$var  = "test";
$var .= "value";

echo $var; // this will give you testvalue


the “.” operator is the string concatenation operator. and “.=” will concatenate strings.


$var = 1;
$var .= 20;

This is same as:

$var = 1 . 20;

the “.=” operator is a string operator, it first converts the values to strings; and since “.” means concatenate / append, the result is the string “120“.


In very plain language, what happens is that whatever is stored in each variable is converted to a string and then each string is placed into a final variable that includes each value of each variable put together.

I use this to generate a random variable of alpha numeric and special characters. Example below:

function generateRandomString($length = 64) {
    $characters = '[email protected]#$%^*()?:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = mb_strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    return $randomString;

then to get the value of $randomString I assign a variable to the function like so

$key = generateRandomString();
echo $key;

What this does is pick a random character from any of the characters in the $characters variable. Then .= puts the result of each of these random “picks” together, in a new variable that has 64 random picks from the $characters string group called $randomString.