3

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.

4
  • 2
    array_walk_recursive Commented Mar 28, 2013 at 7:57
  • 2
    array_walk should be sufficient, since this is only a 2D array. Commented Mar 28, 2013 at 8:13
  • example with array_walk_recursive? Commented Mar 28, 2013 at 8:38
  • 1
    There are many ways to possibly do this, but a loop is the most straight forward thing you can possibly do. Commented Mar 28, 2013 at 9:09

2 Answers 2

7

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

array_walk($array, function(&$a) {
  $a['value'] = 1;
});
Sign up to request clarification or add additional context in comments.

1 Comment

It sounds like you're using an older version of PHP, I should really have mentioned that anonymous functions, such as the above, will only work with PHP 5.3 >
1

Suppose $arr is your array and $yourval is the value to be stored as the new array element. You can do it as follows.

for($i=0;$i<count($arr);$i++){
     $arr[$i]['value'] = $yourval;
}
echo '<pre>';
print_r($arr);//Will display the new array

1 Comment

You are welcome @user1584103 Plz mark it as correct answer if you got the output..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.