The same PHP name in foreach as the outer scope causes rewriting

So, I made the form today and got the variable name with the same name as the name used later in the foreach loop. To my surprise, the foreach loop declaration overwrites the previous variable declaration.

This seems rather strange to me, since I expected the scope as $value => $a to limit the scope of the two variables to the foreach contour.

Here's what happens:

 php > $a = 5; php > $b = array(1,2,3); php > foreach($b as $value => $a){ echo $a; }; 123 php > echo $a; 3 

This is what I expected:

 php > $a = 5; //define a in outer scope php > $b = array(1,2,3); php > foreach($b as $value => $a){ echo $a; /* This $a should be the one from the foreach declaration */ }; 123 php > echo $a; //expecting inner scope to have gone away and left me to get the outer scoped $a 

The same thing happens if I use $a as a foreach key, this stone was more scary:

 php > $a = 5; php > $b = array(1,2,3); php > foreach($b as $a => $b){ var_dump($b); } int(1) int(2) int(3) php > var_dump($b) // => int(3) 

which overwritten the $b array in place but still looped on it.

All in all, it seems a little freaky. My question is, asking where exactly will I find documentation / guidance indicating that this behavior is expected?

+8
scope php foreach behavior
source share
2 answers

Volume in PHP is at the global or function level, there is no block area, see http://php.net/manual/en/language.variables.scope.php

+9
source share

Only functions create a new area. the block area formed by curly braces does not form a new one. In your example, you are in a global area.

+1
source share

All Articles