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
4
  • Because you redeclare $a in your while loop.. making it become the last value of the array.. Commented Sep 16, 2014 at 7:17
  • @Naruto So you mean that the $a is not act like a temp variable? Commented Sep 16, 2014 at 7:23
  • @Naruto Miss understanding.(_). Thanks Commented Sep 16, 2014 at 7:25
  • yeah. if you change $b = '1' and echo $b at the last part, then you got 231. Commented Sep 16, 2014 at 7:27

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.