0

I have 2 arrays stored serialized in my database, when individually unzerialized they might output:

    array(1 => 0, 
    2 => 1, 
    3 => 4, 
    4 => 0, 
    5 => 2);


    array(2 => 3,
    4 => 1);       

I need to merge them in such a way that the values of the 2nd array override those in the 1st, but also preserve any values in array 1 that are not in array 2 for example the ideal output of the 2 combined would be:

    array(1 => 0, 
    2 => 3, 
    3 => 4, 
    4 => 1, 
    5 => 2);

When I attempt to combine them I get the error:

    Fatal error: Unsupported operand types

This is how I have tried (ref: Combine two arrays):

        $array1 = unserialize($row['serialized1']);
        $array2 = unserialize($row['serialized2']);
    $_SESSION['combined_array'] = $array1+$array2;

Also:

    $_SESSION['combined_array'] = unserialize($row['serialized2'])+unserialize($row['serialized1']);

Edit:

I have also tried:

    $_SESSION['combined_array'] = array_merge($array1,$array2); 

This does not error, but does not result in any combined array.

Thank you for any pointers.

Community
  • 1
  • 1
Bernie Davies
  • 419
  • 6
  • 15

1 Answers1

1

Check array_replace(). It's slightly different than array_merge() when dealing with numeric keys:

$array1 = unserialize($row['serialized1']);
$array2 = unserialize($row['serialized2']);
$combined_array = array_replace($array1, $array2);

This works, notice they are reversed from your code:

$combined_array = $array2 + $array1;

You will get the Fatal error: Unsupported operand types if they are not both arrays, empty or otherwise.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • It seems that it was a matter of array2 occassionally being empty - my bad. But this is a neat solution and it does the trick! Thank you. – Bernie Davies May 27 '14 at 18:58
  • Yes, edited. They can be empty, but they must be arrays. [See here](http://sandbox.onlinephpfunctions.com/code/6f83e6e5f0365dede6d9fb30eb259c3cbfbd47e0) – AbraCadaver May 27 '14 at 19:01
  • array_replace presevrves the order - but yes + operator does work. Thanks again! – Bernie Davies May 27 '14 at 19:03