英文:
Order of execution for functions on either side of the assignment operator
问题
$output=[];
假定输出应该像这样:
['value1' => 'value1', 'value2' => 'value2']
因为 next()
优先于 current()
,但这个函数在 PHP8 中运行正常。
为什么呢?赋值不是从右到左吗?
英文:
I want to implement a function
$input = ['key1', 'value1', 'key2', 'value2'];
// $output = ['key1' => 'value1', 'key2' => 'value2'];
$output=[];
do {
$output[current($input)] = next($input);
} while (next($input));
I wrote this code intuitively, but when I reviewed this code today, I pondered if this might be a bug.
I assumed the output should be something like this:
['value1'=>'value1','value2'=>'value2']
because next()
takes precedence over current()
, but this function works fine in PHP8.
Why is this? Isn't assignment from right to left?
答案1
得分: 2
The associativity is from left to right for =
for your case. You can cross check this with the below snippet where t1
gets printed first instead of t2
.
<?php
$output=[];
$output[test('t1')] = test('t2');
function test($str){
echo $str,PHP_EOL;
return rand(10, 100);
}
Hence, your output is [ 'key1' => 'value1','key2' => 'value2']
because current()
gives key1
and next()
advances the internal array pointer and returns the element value which is value1
and the same gets repeated over until the array is looped completely.
英文:
The associativity is from left to right for =
for your case. You can cross check this with the below snippet where t1
gets printed first instead of t2
.
<?php
$output=[];
$output[test('t1')] = test('t2');
function test($str){
echo $str,PHP_EOL;
return rand(10, 100);
}
Hence, your output is [ 'key1' => 'value1','key2' => 'value2']
because current()
gives key1
and next()
advances the internal array pointer and returns the element value which is value1
and the same gets repeated over until the array is looped completely.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论