你可以在 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

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

Can you append strings to variables in PHP?

phpstringoperators

提问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 (+) plusa (.) periodis used for string concatenation.

在与 JavaScript 连接的情况下,PHP 语法几乎没有什么不同。而不是(+) plusa(.) 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;

?>