你可以在 PHP 中将字符串附加到变量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9050685/
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
Can you append strings to variables in PHP?
提问by James
Why does the following code output 0?
为什么下面的代码输出0?
It works with numbers instead of strings just fine. I have similar code in JavaScript that also works. Does PHP not like += with strings?
它适用于数字而不是字符串。我在 JavaScript 中有类似的代码也可以使用。PHP 不喜欢 += 带字符串吗?
<?php
$selectBox = '<select name="number">';
for ($i=1; $i<=100; $i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox += '</select>';
echo $selectBox;
?>
回答by Facebook Staff are Complicit
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
这是因为 PHP 使用句点字符.
进行字符串连接,而不是加号字符+
。因此,要附加到要使用.=
运算符的字符串:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';
回答by Henrik
In PHP use .=
to append strings, and not +=
.
在 PHP 中用于.=
附加字符串,而不是+=
.
Why does this output 0? [...] Does PHP not like += with strings?
为什么这个输出为0?[...] PHP 不喜欢 += 带字符串吗?
+=
is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0
.
+=
是一个算术运算符,用于将一个数与另一个数相加。将该运算符与字符串一起使用会导致自动类型转换。在 OP 的情况下,字符串已转换为 value 的整数0
。
More about operators in PHP:
有关 PHP 中的运算符的更多信息:
回答by Ali Haider
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
在与 JavaScript 连接的情况下,PHP 语法几乎没有什么不同。而不是(+) plus
a(.) period
用于字符串连接。
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>