Order of execution for functions on either side of the assignment operator.

huangapple go评论63阅读模式
英文:

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);
}

Demo

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);
}

Demo

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.

huangapple
  • 本文由 发表于 2023年4月11日 09:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定