In PHP or Python (other languages may apply), why does a value declared in a for
(or foreach
) still exists (and overwrites) in the outer scope?
For example, in PHP:
<?php
$value = 0;
$test = [1,2,3];
foreach ($test as $value) {
echo $value;
}
echo $value;
(execute it (also with a for
loop) here)
will output:
1233
and in Python:
value = 0
test = [1,2,3]
for value in test:
print(value)
print(value)
(execute it here)
will output:
1
2
3
3
It may apply in other languages I'm not still aware of.
The question is why are these for
blocks designed like this?
Why it isn't like (for example) C, where the indexing variable only exists in the for
scope (example here)?