Skip to content
Advertisement

Add a new index to multidimensional array

I have a multidimensional array.

ie.

Array
(
    [0] => Array
        (
            [item_id] => 1
            [item_name] => x

        )


    [1] => Array
        (
            [item_id] => 1
            [item_name] => y

        )

)

I need a way to add a new index to that array .

Array
(
    [0] => Array
        (
            [item_id] => 1
            [item_name] => x
            [value] => 1

        )


    [1] => Array
        (
            [item_id] => 1
            [item_name] => y
            [value] => 1
        )

)

The value may/may not remain the same throughout.

One way to implement this is to loop the array and insert the new index value.

My question is that is there any other better way to do it.

Thanks.

Advertisement

Answer

You don’t need to use array_walk_recursive, you can use array_walk:

array_walk($array, function(&$a) {
  $a['value'] = 1;
});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement