使用分配运算符时无法回显字符串


Can't echo string when used assign operator?

当我使用 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
?>

这是因为您正在使用字符串进行数学运算。

"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