Useful code allowing you to prepend a key/value pair to an array (without the keys being reindexed) :
<?php
$myArray = array($key => $value) + $myArray;
?>
array_unshift with key
array_unshift associative array
array unshift assoc
欢迎各位兄弟 发布技术文章
这里的技术是共享的
Useful code allowing you to prepend a key/value pair to an array (without the keys being reindexed) :
<?php
$myArray = array($key => $value) + $myArray;
?>
array_unshift with key
array_unshift associative array
array unshift assoc
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');
Can't you just do:
$resulting_array = $array2 + $array1;
?
The answer is no. You cannot 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.
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);
@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);
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