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

标签 php operator-precedence

有人可以帮助我理解这段代码吗,因为它似乎不遵循 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/

相关文章:

javascript - 如何查找表中的RowIndex

php - POST 到 Laravel Passport 路由以创建客户端时出现 419 错误

c - 短路算子评估顺序

c - 我正在尝试使用 C 程序查找单词的拼字游戏值

php - 在 mySQL 列中存储随机大小的数组

php - Zend lucene 和 MySql 数据库

php - PDO 准备语句的错误检查

c++ - 我 =++i+++i;在 C++ 中

c# - Lambda 表达式异常

perl - Perl 如何决定对表达式中的项求值的顺序?