Variable scope in for-loop and while-loop [duplicate]

拜拜、爱过 提交于 2020-01-24 09:56:47

问题


I'm new in PHP, I don't understand why the final result of the code below is '233' instead of '231', isn't the $a in foreach is a temp variable?

<?php
    $a = '1';
    $c = array('2', '3');
    foreach($c as $a){
        echo $a ;
    }
    echo $a;
?>

Can anyone help? Thks.

Updated 2014-11-28 Now I know what was my problem. As the accepted answer and this answer have pointed out, neither the foreach nor the while act like functions, they are just normal sentences just like $a='3';. So now I know this is my misunderstanding and it's not just about php, as I've tried in python, it's the same.

a = 123
b = [1, 2, 3]
for a in b:
    print a
print a

回答1:


The $a on line 1 and the $a in the foreach() loop is one and the same object. And after the loop ends, $a has the value 3, which is echoed in the last statement.
According to php.net:

For the most part all PHP variables only have a single scope.

Only in a function does the variable scope is different.
This would produce your desired result '231':

$a = '1';
$c = array('2', '3');
function iterate($temp)
{
    foreach($temp as $a)
        echo $a ;
}
iterate($c)
echo $a;

Because in the iterate() function, $a is independent of the $a of the calling code.
More info: http://php.net/manual/en/language.variables.scope.php




回答2:


The $a in your foreach loop overrides the $a outside the loop.




回答3:


You have taken same name of variable in the foreach loop. your foreach is working as:

  1. on first iteration: it assigning the value 2 means $c[0]'s value to $a.
  2. on next iteration: it assigning the value 3 means $c[1]'s value to $a.
  3. After that the value of $a has become 3 instead if 1.

That's why result is 233. not 231.



来源:https://stackoverflow.com/questions/25862715/variable-scope-in-for-loop-and-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!