6

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
}
Florian Müller
  • 7,448
  • 25
  • 78
  • 120

3 Answers3

11

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.

Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
  • 3
    +1 for being the answer that will work correctly if there is already a `front` item in the array. – salathe Dec 23 '10 at 08:30
  • 1
    @salathe Thank you. But I'm not sure which of the two option (+ or array_merge) the asker really needs. I'll add a note to make him aware of the difference. – Alin Purcaru Dec 23 '10 at 08:39
  • 1
    with both options the item will be at the start of the array, the difference is the value it has. The question makes it clear what value Florian is expecting. – salathe Dec 23 '10 at 09:15
4

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
)
Srisa
  • 967
  • 1
  • 7
  • 17
2

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.

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320