0

I'm looping over a countries object. However, when I reference that object I notice that the second to last element is duplicated, while the last element is skipped. Uruguay appears twice, while America does not appear at all.:

foreach($countries as &$country){
    $country->keywords = array_merge(array($country->name),$country->synonyms);
    var_dump($country->key);
}

var_dump('-----------------------------------------');

foreach($countries as $country){
    var_dump($country->key);
}

exit;

And my output. Scroll all the way to the bottom to see uruguay now appears twice:

string(7) "algeria"
string(9) "argentina"
string(9) "australia"
string(7) "belgium"
string(6) "bosnia"
string(8) "cameroon"
string(5) "chile"
string(8) "columbia"
string(9) "costarica"
string(5) "ivory"
string(7) "croatia"
string(8) "ecquador"
string(7) "england"
string(6) "france"
string(7) "germany"
string(5) "ghana"
string(6) "greece"
string(8) "honduras"
string(4) "iran"
string(5) "italy"
string(5) "japan"
string(6) "mexico"
string(11) "netherlands"
string(7) "nigeria"
string(8) "portugal"
string(6) "russia"
string(5) "korea"
string(5) "spain"
string(11) "switzerland"
string(7) "uruguay"
string(7) "america"
string(41) "-----------------------------------------"
string(7) "algeria"
string(9) "argentina"
string(9) "australia"
string(7) "belgium"
string(6) "bosnia"
string(8) "cameroon"
string(5) "chile"
string(8) "columbia"
string(9) "costarica"
string(5) "ivory"
string(7) "croatia"
string(8) "ecquador"
string(7) "england"
string(6) "france"
string(7) "germany"
string(5) "ghana"
string(6) "greece"
string(8) "honduras"
string(4) "iran"
string(5) "italy"
string(5) "japan"
string(6) "mexico"
string(11) "netherlands"
string(7) "nigeria"
string(8) "portugal"
string(6) "russia"
string(5) "korea"
string(5) "spain"
string(11) "switzerland"
string(7) "uruguay"
string(7) "uruguay"
A F
  • 7,424
  • 8
  • 40
  • 52

1 Answers1

2
foreach($countries as &$country){
    $country->keywords = array_merge(array($country->name),$country->synonyms);
    var_dump($country->key);
}
unset($country);

var_dump('-----------------------------------------');

foreach($countries as $country){
    var_dump($country->key);
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • It works because you're unsetting a reference, not the actual array entry; otherwise the reference is still pointing to the last entry in your array when you start iterating over that array again, so it overwrites the entry pointed to by that reference – Mark Baker Jun 25 '14 at 19:13
  • See my answer to [this question](http://stackoverflow.com/questions/4969243/strange-behavior-of-foreach/4969286#4969286) for an explanation – Mark Baker Jun 25 '14 at 19:16