131

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');
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Colin Brock
  • 21,267
  • 9
  • 46
  • 61
  • See also: [Differences between array_replace() and array_merge() and + (array union operator)](https://stackoverflow.com/q/34367511/2943403) – mickmackusa Nov 10 '22 at 22:48

6 Answers6

253

Can't you just do:

$resulting_array = $array2 + $array1;

?

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 16
    See also array_merge() and its difference from using the + operator: http://br.php.net/manual/en/function.array-merge.php#92602 – Havenard Sep 03 '09 at 01:33
  • 2
    @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 Brock Sep 03 '09 at 01:36
  • 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 Sep 03 '09 at 01:37
38

You cannot directly prepend an associative array with a key-value pair.

However, you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.

The syntax is below.

$new_array = array('new_key' => 'value') + $original_array;

Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
PHPguru
  • 491
  • 4
  • 5
  • "overwrites keys and does not preserve numeric keys"... a) how does the union operator ("+") handle "duplicate" keys? re: not preserve numeric keys : likely desired – Brad Kent May 28 '19 at 02:35
20

In your situation, you want to use array_merge():

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

To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():

array_merge(array($key => $value), $myarray);
mvpetrovich
  • 209
  • 2
  • 2
6

Using the same method as @mvpetrovich, you can use the shorthand version of an array to shorten the syntax.

$_array = array_merge(["key1" => "key_value"], $_old_array);

References:

PHP: array_merge()

PHP: Arrays - Manual

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Bryce Gough
  • 81
  • 1
  • 2
5

@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 = $array1 + $array2;
ksort($resulting_array);
Dvir Berebi
  • 1,406
  • 14
  • 25
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 4
    As a late note, `ksort` returns boolean, so the above needs to be done as two statements not one, e.g. `$a = $array1 + $array2; ksort($a);`, otherwise `$resulting_array` will be a boolean value not the array you were expecting. – El Yobo Oct 17 '11 at 22:39
1

If using Laravel, you can use prepend on a collection instance

 collect(['b' => 'b', 'c' => 'c'])->prepend('a','a');

// ['a'=>'a', 'b' => 'b', 'c' => 'c']

https://laravel.com/docs/9.x/collections#method-prepend

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
  • Nicely done. I wish more users would find canonicals to post modern techniques on. This question is asking how to prepend more than one associative element to the array. Does this approach have the capacity to prepend multiple associative elements to the array/collection or do you have to call the `prepend()` method _n_ times? – mickmackusa Nov 10 '22 at 22:50