"John"), array("name"=>"Rob"), array("name"=...">

Strange php array and foreach loop behavior

I have the following code:

$array = array( array("name"=>"John"), array("name"=>"Rob"), array("name"=>"Tom"), ); foreach($array as &$el) $el["age"]=23; foreach($array as $el) echo $el["name"] . " is: " . $el["age"] . " years old<br>"; 

I expect something like this:

 John is: 23 years old Rob is: 23 years old Tom is: 23 years old 

but I really get the following:

 John is: 23 years old Rob is: 23 years old Rob is: 23 years old 

Why? In the first foreach loop, I use the link to edit the source array.

+5
source share

All Articles