0
<?php
$array = array(
    array('key' => 'value'),
    array('key' => 'value'),
    array('key' => 'value')
);

foreach($array as $a) {
    $a['anotherkey'] = 'anothervalue';
}
?>

I am trying to add another key value ('anotherkey' => 'anothervalue') into each array inside $array. However the above code does not work and I can't seem to figure out why, is it because the $a['anotherkey'] could not add the value to the real array ? And what is the proper way to adding the keyvalue pair into each of the array inside $array using foreach loop ? Thank you.

1 Answer 1

2

Try this:

 $array = array(
   array('key' => 'value'),
   array('key' => 'value'),
   array('key' => 'value')
);

foreach($array as &$a) {
  $a['anotherkey'] = 'anothervalue';
}

print_r($array);

Pass By Reference used above. Read here : http://php.net/manual/en/language.references.pass.php

Hope this helps.

Sign up to request clarification or add additional context in comments.

6 Comments

Wow, it works, thank you so much. I wonder why though, could you care to explain a little bit on the '&' sign and why without it the loop doesn't work ? Thx :)
@Charas I have added the link above for you. Please go through it. :)
Great ! Thanks a lot.
@Charas Glad to help :)
There's a bug in PHP5/7 make sure you unset($a) after the foreach loop or you can get some funny bugs.
|

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.