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?
scope php foreach behavior
EdgeCaseBerg
source share