Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 459
shellbye Avatar asked Sep 16 '25 21:09

shellbye


1 Answers

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

like image 172
Ganesh Jadhav Avatar answered Sep 19 '25 10:09

Ganesh Jadhav