0

I have an array. It looks like this

$choices = array(
array('label' => 'test1','value' => 'test1'),
array('label' => 'test2','value' => 'test2'),
array('label' => 'test3','value' => 'test3'),
)

Now i would like to prepend this value in $choices array

array('label' => 'All','value' => 'all'),

It looks like I cannot use array_unshift function since my array has keys.

Can someone tell me how to prepend?

PrivateUser
  • 4,474
  • 12
  • 61
  • 94
  • yes, it'll work just fine. even though you don't have explicitly defined keys in $choices, every **HAS** to have keys. – Marc B Mar 07 '13 at 18:45
  • I don't see why you can't use `array_unshift`; every array has keys. – jeroen Mar 07 '13 at 18:45
  • It looks like you can. The outer array is a list, with numeric keys. What you put inside (a distinct associative array) doesn't matter. – mario Mar 07 '13 at 18:45
  • copy of http://stackoverflow.com/questions/1371016/php-prepend-associative-array-with-literal-keys – Sumit Bijvani Mar 07 '13 at 18:49

1 Answers1

2

Your $choices array has only numeric keys so array_unshift() would do exactly what you want.

$choices = array(
    array('label' => 'test1','value' => 'test1'),
    array('label' => 'test2','value' => 'test2'),
    array('label' => 'test3','value' => 'test3'),
);
echo $choices[0]['label']; // echoes 'test1'

$array_to_add = array('label' => 'All','value' => 'all');
array_unshift($choices, $array_to_add);

/* resulting array would look like this:
$choices = array(
    array('label' => 'All','value' => 'all')
    array('label' => 'test1','value' => 'test1'),
    array('label' => 'test2','value' => 'test2'),
    array('label' => 'test3','value' => 'test3'),
);
*/
echo $choices[0]['label']; // echoes 'All'
Mike Brant
  • 70,514
  • 10
  • 99
  • 103