2

I was doing a script where I needed to work with every single value of an array, so I helped myself with the trick of using the assignment operator in the value parameter of the foreach in order to edit the array value directly, and I noticed that every last value of the foreach give a strange problem.

That's the PHP script:

<?php
$array = array('test1', 'test2', 'test3', 'test4');

var_dump($array);
echo "<br />";

foreach ($array as &$value)
{
    // do something
    $value = $value . "foo";
}

var_dump($array);
echo "<br />";

foreach ($array as $value)
{
    echo $value . "<br />";
}

And that's the output:

array(4) { [0]=> string(5) "test1" [1]=> string(5) "test2" [2]=> string(5) "test3" [3]=> string(5) "test4" } 
array(4) { [0]=> string(8) "test1foo" [1]=> string(8) "test2foo" [2]=> string(8) "test3foo" [3]=> &string(8) "test4foo" } 
test1foo
test2foo
test3foo
test3foo

As you notice, the var_dump of the array after the foreach, in the last value, there's the assignment operator in front of the type of value (string).

And when I try to output every value of the array, it doesn't give me the last value "test4foo" but it repeat the precedent value (penultimate).

Is it a bug? Can anyone explain it?

Keaire
  • 879
  • 1
  • 11
  • 30
  • I'd guess if you use any other name than `$value` in the second `foreach` this does not happen. This name still is under some influence of the previous reference-assignment (`&`). Not sure about the technical details right now unfortunately. – Tobias K. Aug 13 '18 at 18:24
  • try to add `&` infront of `$value` in your last loop, as you can see the last item `&string(8) "test4foo"` is a reference, so it might help with `foreach ($array as &$value)` – keja Aug 13 '18 at 18:25
  • 1
    _Warning Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()._ – AbraCadaver Aug 13 '18 at 18:28
  • 2
    I think this is exactly the same question with a valid/understandable answer and how to fix it: https://stackoverflow.com/a/18061470/7362396 – Tobias K. Aug 13 '18 at 18:29

0 Answers0