4

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
Community
  • 1
  • 1
shellbye
  • 4,620
  • 4
  • 32
  • 44

3 Answers3

6

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

Ganesh Jadhav
  • 2,830
  • 1
  • 20
  • 32
2

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

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
0

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.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75