What happens behind the scene of PHPs foreach?

Viewed 117

Experiments in PHP 7.1 (docker image nanoninja/php-fpm:7.1)

In next piece of code everything clear:

$arr1 = [1, 2, 3];

foreach ($arr1 as &$value) {
    $value *= 2;
}

We have array $arr1 and multiply all values by 2. Result:

array(3) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  &int(6)
}

But what happens in this statement:

$arr1 = [1, 2, 3];

foreach ($arr2 = $arr1 as &$value) {
    $value *= 2;
}

Result of both arrays $arr1 and $arr2 will unchangeable:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Why is it happens? I know that in PHP > 7 foreach works with copy of array but with copy of which array it works in this case $arr1 or $arr2. And why & don't work?

1 Answers

foreach only works with a copy of the array in the normal by-value mode, not in by-reference mode. So that change in PHP 7 is not relevant to this code.

But in your second code block, you're not using a variable as the array to iterate over, so there's nothing to make a reference to. Instead, you have an expression, and the value of the expression is a copy of the array. It's essentially equivalent to doing:

$temp = $array1 = $array2;
foreach ($temp as &$value) {
    $value *= 2;
}

This will update $temp, but not $array1 or $array2.

Related