PHP prepend associative array with literal keys?

Colin Brock picture Colin Brock · Sep 3, 2009 · Viewed 58.4k times · Source

Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.

As an example I'd like to do the following:

$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange');
$array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry');

// prepend magic

$resulting_array = ('fruit1'=>'cherry', 
                    'fruit2'=>'blueberry', 
                    'fruit3'=>'apple', 
                    'fruit4'=>'orange');

Answer

cletus picture cletus · Sep 3, 2009

Can't you just do:

$resulting_array = $array2 + $array1;

?