PHP: Array_unshift an not numeric index [duplicate]
Just wanted to add a new parameter in the front of my array with array_unshift, but: If I do it like usual, it has an numeric index. How can I decline the index, e.g. something like that...
<?php
$queue = array("a", "B");
array_unshift($queue, "front" => "hello" ); //Not working, this is my question ;)
?>
The array would then look like
Array {
front => hello
0 => a
1 => B
}
array_push
, array_pop
, array_shift
, array_unshift
are designed for numeric arrays.
You can use one of the array_merge
solutions some people already mentioned or you can use the +
operator for arrays:
$queue = array('front' => 'Hello') + $queue;
Note: When using array_merge
the items with the same keys from the second array will overwrite the ones from the first one, so if 'front' already exists in $queue
it will not be overwritten, but only brought to the front. On the other hand if you use +
, the new value will be present in the result and be at the front.
Looks like array_unshift cannot do what you want. Try this:
$queue = array('a', 'B');
$queue = array_merge(array('front' => 'hello'), $queue);
This gives the result you want.
Array ( [front] => hello [0] => a [1] => b )
Use array_merge
:
$new_queue = array_merge(array("front"=>"hello"), $queue);
The reason why you must use array_merge
and not array_unshift
is because the latter only works on numerically indexed arrays.
精彩评论