phparray-mergearray-combine

PHP combine two associative arrays with different keys


I want to combine two associative arrays with different amount of keys and keep all the keys in the final array even if they are null or empty

I have tried array_merge but the keys that are not present in both arrays are removed.

Here are the two arrays:

$array1 = array(
    array("email" => "user1@mail", "login" => "user1", "phone" => "123", "color" => "red"),
    array("email" => "user2@mail", "login" => "user2", "phone" => "456", "color" => "blue"),
);

$array2 = array(
    array("email" => "user3@mail", "login" => "user3"),
    array("email" => "user4@mail", "login" => "user4"),
);

And this is what I want to get:

$arrayMerge = array(
    array("email" => "user1@mail", "login" => "user1", "phone" => "123", "color" => "red"),
    array("email" => "user2@mail", "login" => "user2", "phone" => "456", "color" => "blue"),
    array("email" => "user3@mail", "login" => "user3", "phone" => NULL, "color" => NULL),
    array("email" => "user4@mail", "login" => "user4", "phone" => NULL, "color" => NULL),
);

The value NULL could also be empty, all I want is to keep the key.


Solution

  • array_merge will get you most of the way there. I see no evidence that "keys which are not present in both arrays are removed", as you claimed.

    Before the merge, a quick loop to add in keys in $array2 which you expect might be missing will finish the job.

    You could also do that afterwards on the merged array, but you don't need to unless there might also be items in $array1 which are missing some fields.

    $array1 = array(
        array("email" => "user1@mail", "login" => "user1", "phone" => "123", "color" => "red"),
        array("email" => "user2@mail", "login" => "user2", "phone" => "456", "color" => "blue"),
    );
    
    $array2 = array(
        array("email" => "user3@mail", "login" => "user3"),
        array("email" => "user4@mail", "login" => "user4"),
    );
    
    foreach ($array2 as &$record)
    {
        if (!isset($record["phone"])) {
            $record["phone"] = null;
        }
        if (!isset($record["color"])) {
            $record["color"] = null;
        }
    }
    
    $merged = array_merge($array1, $array2);
    
    var_export($merged);
    

    This outputs:

    array (
      0 => 
      array (
        'email' => 'user1@mail',
        'login' => 'user1',
        'phone' => '123',
        'color' => 'red',
      ),
      1 => 
      array (
        'email' => 'user2@mail',
        'login' => 'user2',
        'phone' => '456',
        'color' => 'blue',
      ),
      2 => 
      array (
        'email' => 'user3@mail',
        'login' => 'user3',
        'phone' => NULL,
        'color' => NULL,
      ),
      3 => 
      array (
        'email' => 'user4@mail',
        'login' => 'user4',
        'phone' => NULL,
        'color' => NULL,
      ),
    )
    

    Working demo: https://3v4l.org/eSKMo