0

I was playing with PHP recently and wanted to assign variable in foreach loop and pass value by reference at the same time. I was a little bit surprised that didn't work. Code:

$arr = array(
    'one' => 'xxxxxxxx',
    'two' => 'zzzzzzzz'
);

foreach ($foo = $arr as &$value) {
    $value = 'test';
}

var_dump($foo);

Result:

array(2) { ["one"]=> string(8) "xxxxxxxx" ["two"]=> string(8) "zzzzzzzz" }

The following approach obviously does work:

$arr = array(
    'one' => 'xxxxxxxx',
    'two' => 'zzzzzzzz'
);

$foo = $arr;

foreach ($foo as &$value) {
    $value = 'test';
}

var_dump($foo);

Result:

array(2) { ["one"]=> string(4) "test" ["two"]=> &string(4) "test" }

Does someone know why those snippets are not equivalent and what is being done behind the scenes?

LF00
  • 27,015
  • 29
  • 156
  • 295
Ness
  • 1
  • 2
  • 1
    [Are arrays in PHP passed by value or by reference?](https://stackoverflow.com/q/2030906/6521116) – LF00 Jun 18 '17 at 01:45

2 Answers2

1

$foo = $arr is trans by value, not reference, you should use $foo = &$arr. You can refer to Are arrays in PHP passed by value or by reference?

try this, live demo.

$arr = array(
    'one' => 'xxxxxxxx',
    'two' => 'zzzzzzzz'
);

foreach ($foo = &$arr as &$value) {
    $value = 'test';
}

var_dump($foo);
LF00
  • 27,015
  • 29
  • 156
  • 295
  • Ok, but doing it this way we change the 'arr' array too ;) I don't want to do this. With this approach there is no point to reassign variable to 'foo' - it doesn't make sense. – Ness Jun 18 '17 at 01:49
0
foreach ($foo = $arr as &$value) {
    $value = 'test';
}

first you assign the value of $arr[0] to $foo[0] then take that value and make that value = 'test' (this will not change $arr or $foo values "useless statement")

But here

$foo = $arr;
foreach ($foo as &$value) {
    $value = 'test';
}

first you asign $arr to $foo then go to for each statement , get the values of $foo and modify it ex: $foo[0]='test' , $foo[1]='test' ...