Variable Scope In For-loop And While-loop
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?
Solution 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 echo
ed 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');
functioniterate($temp)
{
foreach($tempas$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
Solution 2:
The $a
in your foreach
loop overrides the $a
outside the loop.
Solution 3:
You have taken same name of variable in the foreach
loop. your foreach is working as:
- on first iteration: it assigning the value 2 means
$c[0]
's value to$a
. - on next iteration: it assigning the value 3 means
$c[1]
's value to$a
. - After that the value of
$a
has become 3 instead if 1.
That's why result is 233. not 231.
Post a Comment for "Variable Scope In For-loop And While-loop"