PHP添加和连接困惑时 [英] Php confused when adding and concatenating
问题描述
考虑这个PHP code:
Consider this php code:
<?php
$row = array('a'=>1,'b'=>2,'c'=>3);
echo "sum: ".$row['a']+$row['b']+$row['c'];
echo "\n";
echo "sum: ".($row['a']+$row['b']+$row['c']);
echo "\n";
?>
在执行形式的终端输出是:
when executed form a terminal the output is:
$ php code.php
5
sum: 6
为什么在第一回波的总和失败,字符串总和:不打印?似乎PHP是不麻烦时$行中的元素之和括在括号中。 PHP是这种怪异的行为记录?
why in the first echo the sum fails and the string "sum: " is not printed? It seems that php is not in trouble when the sum of the elements of $row is enclosed in parenthesis. Is this weird behaviour of php documented?
谢谢!
更新:看来,这是由于级联和运营商总和的precedence,正如你们许多人指出。非常有趣。感谢你们!!
Update: It seems that this is due to the precedence of the concatenation and sum operators, as many of you pointed. Very interesting. Thank you guys!!
推荐答案
似乎在PHP中的 +
运营商具有较高的precedence比。
(即。
结合在前)。你的第一个前pression然后进行评估,如:
Seems that in PHP the +
operator has higher precedence than the .
(i.e. .
binds first). Your first expression then is evaluated like:
("sum: ".$row['a'])+$row['b']+$row['c']
("sum: 1"+$row['b'])+$row['c']
2+$row['c']
5
(添加字符串总和:1
来一个数字,字符串是<一个href=\"http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion\">coerced以零值,使之和的结果是 2
)
(when adding the string "sum: 1"
to a number, the string is coerced to the value zero, so the result of the sum is 2
)
更新:其实他们有相同precedence ,但因为他们是左结合,在。
首先计算。
Update: Actually they have the same precedence, but since they're left associative, the .
is evaluated first.
这篇关于PHP添加和连接困惑时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!