views:

587

answers:

2

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');
+3  A: 

Can't you just do:

$resulting_array = $array2 + $array1;

?

cletus
See also array_merge() and its difference from using the + operator:http://br.php.net/manual/en/function.array-merge.php#92602
Havenard
@cletus: Sheesh. Yeah, I can. Not sure what made me think I couldn't or what wasn't working before. Thanks for the response.
Colin
@Havenard: Thanks for the additional info.
Colin
It is worth noting the difference but that difference is relevant for preserving numeric keys and this array is a "pure" associative array with string keys.
cletus
+1  A: 

@Cletus is spot on. Just to add, if the ordering of the elements in the input arrays are ambiguous, and you need the final array to be sorted, you might want to ksort:

$resulting_array = ksort($array1 + $array2);
karim79
@karim: That's helpful - thanks.
Colin