Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Array_unshift an not numeric index

Tags:

arrays

php

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
}
like image 660
Florian Müller Avatar asked Dec 23 '10 07:12

Florian Müller


1 Answers

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.

like image 102
Alin Purcaru Avatar answered Sep 22 '22 13:09

Alin Purcaru