How can I add an item to the beginning of an associative array? For example, say I have an array like this:
$arr = array('key1' => 'value1', 'key2' => 'value2');
When I add something to it as in $arr['key0'] = 'value0';
, I get:
Array ( [key1] => value1 [key2] => value2 [key0] => value0 )
How do I make that to be
Array ( [key0] => value0 [key1] => value1 [key2] => value2 )
Thanks,
Tee
Use the array_merge() Function to Add Elements at the Beginning of an Associative Array in PHP. To add elements at the beginning of an associative, we can use the array union of the array_merge() function.
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);
You could use the union operator:
$arr1 = array('key0' => 'value0') + $arr1;
or array_merge
.
One way is with array_merge
:
<?php
$arr = array('key1' => 'value1', 'key2' => 'value2');
$arr = array_merge(array('key0' => 'value0'), $arr);
Depending on circumstances, you may also make use of ksort
.
$array = array('key1' => 'value1', 'key2' => 'value2');
array_combine(array_unshift(array_keys($array),'key0'),array_unshift(array_values($array),'value0'))
function unshift( array & $array, $key, $val)
{
$array = array_reverse($array, 1);
$array[$key] = $val;
$array = array_reverse($array, 1);
return $array;
}
If you don't want to merge the arrays you could just use ksort()
on the array before iterating over it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With