Is it feasible to prepend a literal key=>value pair to an associative array? I know array unshift() works with number keys, but I’m expecting for something that works with literal keys as well.
As an example, here’s what I’d like to do:
$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange'); $array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry'); // prepend magic $resulting_array = ('fruit1'=>'cherry', 'fruit2'=>'blueberry', 'fruit3'=>'apple', 'fruit4'=>'orange');
Asked by Colin Brock
Why don’t you just:
$resulting_array = $array2 + $array1;
Answered by cletus
A key-value pair cannot be explicitly prepended to an associative array.
The union operator +, on the other hand, can be used to build a new array with the new key-value pair at the beginning. However, the result is a whole new array, and building the new array is O(n) in complexity.
The syntax is shown below.
$new_array = array('new_key' => 'value') + $original_array;
Note: array merge should not be used (). numeric keys are not preserved when using array merge() since it overwrites them.
Answered by PHPguru
You should use array merge() in your situation:
array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));
Instead of array unshift(), use array merge() to prepend a single value to an associative array:
array_merge(array($key => $value), $myarray);
Answered by mvpetrovich
You may use the shorthand version of an array to shorten the syntax in the same way that @mvpetrovich did.
$_array = array_merge(["key1" => "key_value"], $_old_array);
Manual for PHP Arrays
Answered by Bryce Gough
@Cletus is absolutely correct. Just a note: if the ordering of the elements in the input arrays is questionable and you need the final array to be sorted, you should use ksort:
$resulting_array = $array1 + $array2; ksort($resulting_array);
Answered by karim79
Post is based on https://stackoverflow.com/questions/1371016/php-prepend-associative-array-with-literal-keys