gpt4 book ai didi

php - PHP中递增/递减运算符的优先级

转载 作者:行者123 更新时间:2023-12-04 05:17:30 24 4
gpt4 key购买 nike

有人可以帮助我理解这段代码,因为它似乎没有遵循 PHP 中递增/递减运算符的优先级和关联性原则:(这是来自 PHP 手册递增/递减操作符页面中的评论 -
http://php.net/manual/en/language.operators.increment.php )

第一个例子 -

$a = [ 0, 1, 2 ];
$i = 0;
$a[$i++] = $i;

var_dump( $a );

/* 这里是输出:
array (size=3)
0 => int 1
1 => int 1
2 => int 2

这是我对正在发生的事情的解释:
1. Array index gets calculated, so $a[$i++] is $a[0]
2. Then rval gets calculated (which after $i++ in the step above) is now 1
3. The value of the expression gets calculated which is 1.

到目前为止一切顺利。
*/

第二个例子 -
$a = [ 0, 1, 2 ];
$i = 0;
$a[$i] = $i++;

var_dump( $a );

/* 这是输出:
array (size=3)
0 => int 0
1 => int 0
2 => int 2

这是我对正在发生的事情的解释:
1. The array index gets calculated which should be 0 ($a[0]), but ACTUALLY it is 1 ($a[1])
2. The rval gets calculated , which is $i++ , so the value now is 0.
3. The expression value gets calculated , which should be 1 after $i++ in the step above, but ACTUALLY it is 0.

所以从根本上说,我无法理解上面第二个示例中的第 1 步和第 3 步。
*/

最佳答案

来自与您的代码相同的评论:

Assignment index expressions and value expressions are both evaluated before any actual assignment happens, that means that no mater where you place your post incr/decr you may not be getting the result you had in mind.



上线 $a[$i++] = $i; , 两个索引表达式 $i++关于 LHS 和值表达式 $i在分配之前正在评估 RHS。

关于php - PHP中递增/递减运算符的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com