What does the .= operator mean in PHP?

前端 未结 4 1926
逝去的感伤
逝去的感伤 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:31

    the "." operator is the string concatenation operator. and ".=" will concatenate strings.

    Example:

    $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".

    0 讨论(0)
  • 2021-01-01 09:35

    This is for concatenation

    $var  = "test";
    $var .= "value";
    
    echo $var; // this will give you testvalue
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-01 09:45

    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.

    0 讨论(0)
提交回复
热议问题