0

Can someone explain in detail what is hapenning here, because in the second loop pass, I get result "one" "two" "three" "three"?

$a = array("one", "two", "three", "four");

foreach ($a as &$e) {
    echo $e . PHP_EOL;
}

foreach ($a as $e) {
    echo $e . PHP_EOL;
}
Vladimir Despotovic
  • 3,200
  • 2
  • 30
  • 58
  • 1
    You don't see the difference in your script, as you're not doing anything what a reference would help you achieving. Take a look at this script https://3v4l.org/brnqo – Charlotte Dunois Aug 23 '16 at 22:03
  • 1
    http://www.php.net/manual/en/language.references.php –  Aug 23 '16 at 22:03
  • 1
    Once you turn `$e` into a reference it **STAYS** a reference, and the values you're assigning in your second foreach will overwrite the final value of the array because that's the last thing `&$e` was pointing at in the first loop. – Marc B Aug 23 '16 at 22:04
  • 1
    http://stackoverflow.com/questions/3307409/php-pass-by-reference-in-foreach – Martin Aug 23 '16 at 22:06
  • 1
    @MarcB No, not really. It's a reference within the loop. Otherwise this would actually print two random numbers and not one https://3v4l.org/3UZQv Unless you meant something else, then you need to elaborate. – Charlotte Dunois Aug 23 '16 at 22:07
  • 1
    `$e` stays defined after the first loop finishes, and it'll STILL be a reference... – Marc B Aug 23 '16 at 22:08
  • 1
    Try this: `$arr = [1,2,3,4]; foreach($arr as &$e) { 1; } $e = 7; print_r($arr);`. you'll see that the array is now 1,2,3,7. and note that the change was done OUTSIDE of the foreach. $e became a reference, and STAYED a reference. – Marc B Aug 23 '16 at 22:09
  • 1
    @Dagon `Dagon.addNewDuplicateToRepository->` http://stackoverflow.com/questions/4969243/strange-behavior-of-foreach :) – Rizier123 Aug 23 '16 at 22:13
  • 1
    @Rizier123 my dupe list folder is to large as it is :) –  Aug 23 '16 at 22:17
  • 1
    @MarcB Ah, that's what you meant. Yes, that's the case. Imo it's a bug and should be fixed. But looks like it's a design feature. – Charlotte Dunois Aug 23 '16 at 22:20
  • I saw the explanation on the existing question, and I think I got it now. The $v points to same memory location as $a[3], so every time it changes its value - the $a[3] changes the value as well. The rest is just following the logic of this described process. – Vladimir Despotovic Aug 24 '16 at 20:42

0 Answers0