Skip to content
Advertisement

Failing to array_merge(), same output prior to loop

I’ve seen numerous related questions, none answered this for me – I apologize if that’s due to my lack of knowledge…

I have an array, $contacts, where each record looks like the below, with 1-many contacts:

JavaScript

I want to combine any like names, per record, keeping the relevant contact info. Trying this:

JavaScript

My expected/desired output would be:

JavaScript

But the loop isn’t having any effect, at least not that I can find. My actual output matches the initial array.

What am I missing here?

EDIT/UPDATE: Simple mix up on passing by reference/value. Thanks @Barmar for the quick solution. No changes were reflected in the array because I never actually told php to update those values. Shocking how that works.

Advertisement

Answer

There’s two reasons why your code doesn’t work:

  1. Assigning to $contact doesn’t change the array, it just reassigns the variable.
  2. array_merge() doesn’t modify the array in place, it returns a new array.

You can solve both problems by making $contact a reference variable.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement