PHP 中的 .= 运算符是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14846570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:03:24  来源:igfitidea点击:

What does the .= operator mean in PHP?

phpoperatorsequals

提问by codacopia

I have a variable that is being defined as

我有一个被定义为的变量

$var .= "value";

How does the use of the dot equal function?

dot equal函数的使用方法是什么?

回答by Blender

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.

$x .=不同之处在于$x = $x .前者是就地的,但后者重新分配了$x

回答by Prasanth Bendra

This is for concatenation

这是为了串联

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

echo $var; // this will give you testvalue

回答by AlphaMale

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

" .=" 运算符是一个字符串运算符,它首先将值转换为字符串;由于“ .”表示连接/追加,因此结果是字符串“ 120”。

回答by airider74

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

然后为了获得 $randomString 的值,我将一个变量分配给函数,就像这样

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

这样做是从 $characters 变量中的任何字符中选择一个随机字符。然后 .= 将这些随机“选择”中的每一个的结果放在一个新变量中,该变量具有来自名为 $randomString 的 $characters 字符串组的 64 个随机选择。