使用assign运算符时,不能回显字符串吗?

时间:2016-03-11 08:30:12

标签: php

当我使用foreach运行我的变量数组时,我发现当使用加法运算符时,不显示回声字符串。但是回显只有赋值运算符才能显示。使用加法不能回显字符串的原因是什么运营商?

<?php
 $key = 3;
 echo $key+1;echo "<br>";      // 4
 echo "The answer is ".++$key; // The answer is 4
 echo "The answer is ".$key+1; // 1
 //last echo is why can't display string and not getting 4
?>

1 个答案:

答案 0 :(得分:2)

那是因为你正在用字符串进行数学运算。

"The answer is ".$key+1

相同
"The answer is 3" + 1 which equals 1;

您需要使用()来清除范围

$key = 3;
"The answer is ".($key+1) === "The answer is 4"

另外

echo "The answer is ".++$key; // The answer is 4
echo "The answer is ".($key+1); // This would be 5, beause you're incrementing $key by 1 beforehand