1

How can i push variable into multidimensional array php? when I give key for the tow array it worked, but when I delete keys it doesn't work : I mean :

$array1= array('x'=>array('id'=>7,'code'=>4444),'y'=>array('id'=>8,'code'=>3333));
whith

array_push($array1['x'],$newdata); 

I dont want to generate x, y ... , I want let it automatically generated.

I want a result look like that:

Array
(
    [0] => Array
        (
            [id] => 7
            [code] => 4444
            [newData] => 1111
        )

    [1] => Array
        (
            [id] => 8
            [code] => 3333
            [newData] => 1111
        )

)

Here what i tried:

<?php
$array1= array(array('id'=>7,'code'=>4444),array('id'=>8,'code'=>3333));
$newdata = 1111;
foreach ($array1 as $item ){
    array_push($item,$newdata);
}
print_r($array1);
1
  • 1
    Use a reference to $item in the foreach loop. (foreach($array1 as &$item) Commented Aug 2, 2019 at 14:49

2 Answers 2

4

You need to be able to update the original array in the correct way. Firstly to update the original data (in this way) use &$item. Secondly add the item with the correct key rather than use just using array_push() - array_push() will add it with a key of 0 (in this case)...

foreach ($array1 as &$item ){
    $item['newData'] = $newdata;
}

gives the output...

Array
(
    [0] => Array
        (
            [id] => 7
            [code] => 4444
            [newData] => 1111
        )

    [1] => Array
        (
            [id] => 8
            [code] => 3333
            [newData] => 1111
        )

)

Or using the original array and fetching the key in the foreach...

foreach ($array1 as $key => $item ){
    $array1[$key]["newData"] = $newdata;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. That what I want exactly. Thanks
1

I don't think you need to use push. When for loop we need to use & symbol before $ to reference item variable

$array1= array(array('id'=>7,'code'=>4444),array('id'=>8,'code'=>3333));
$newdata = 1111;
foreach ($array1 as &$item ){
    $item["newData"] = $newdata;
}
print_r($array1);

Just do it this way.

1 Comment

Thank you so much. That what I want exactly. Thanks bro

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.