What does the .= operator mean in PHP?

前端 未结 4 1925
逝去的感伤
逝去的感伤 2021-01-01 08:57

I have a variable that is being defined as

$var .= \"value\";

How does the use of the dot equal function?

4条回答
  •  北海茫月
    2021-01-01 09:41

    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 = '0123456789-!@#$%^*()?: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.

提交回复
热议问题