2

I have an array of arrays, and I am trying to foreach loop through and insert new item into the sub arrays.

take a look below

            $newarray = array(
                    array("id"=>1,"quantity"=>2),
                    array("id"=>1,"quantity"=>2),
                    array("id"=>1,"quantity"=>2),
           );

           foreach($newarray as $item){
                $item["total"] = 9;
            }
           echo "<br>";
           print_r($newarray);

The result just give me the original array without the new "total". Why ?

1

2 Answers 2

3

Because $item is not a reference of $newarray[$loop_index]:

foreach($newarray as $loop_index => $item){
    $newarray[$loop_index]["total"] = 9;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the right answer. Will accept it after 10 minute timer.
1

The foreach() statement gives $item as an array: Not as the real value (consuming array). That meaning it can be read but not changed unless you then overwrite the consuming array.

You could use the for() and loop through like this: see demo.

Note: This goes all the way back to scopes, you should look into that.

Comments

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.