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?

4
  • yes, it'll work just fine. even though you don't have explicitly defined keys in $choices, every HAS to have keys. Commented Mar 7, 2013 at 18:45
  • I don't see why you can't use array_unshift; every array has keys. Commented Mar 7, 2013 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. Commented Mar 7, 2013 at 18:45
  • copy of stackoverflow.com/questions/1371016/… Commented Mar 7, 2013 at 18:49

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.