2

I am trying to iterate through a simple php array, and have run into bizarre behavior that is causing iteration to terminate early. My php version is 5.6.3.

The following code prints the numbers 1 through 5, as expected...

$values = array(1, 2, 3, 4, 5);

    foreach ($values as $v)
        //$temp_variable = $v;
        echo "v: " . "$v" . "\n";

enter image description here

However, if I uncomment the line with the temporary variable, like so, we only get one iteration!

$values = array(1, 2, 3, 4, 5);

    foreach ($values as $v)
        $temp_variable = $v;
        echo "v: " . "$v" . "\n";

enter image description here

This seems extremely bizarre. How could the act of creating an unused temporary variable cause our loop to go off-the-rails? Any advice would be appreciated, thank you!

zt1983811
  • 1,011
  • 3
  • 14
  • 34
Austin Yarger
  • 89
  • 2
  • 8

1 Answers1

4

This is not bizarre, if you don't encompass the code in curly braces {} then foreach only executes the line immediately after it:

foreach ($values as $v)
    $temp_variable = $v; //foreach ONLY runs this line in the loop
    echo "v: " . "$v" . "\n";

Change it to:

foreach ($values as $v) {
    $temp_variable = $v;
    echo "v: " . "$v" . "\n";
}

Now everything inside the braces is part of the loop. This is the same with basically every other control structure in PHP:

if($condition === TRUE)
    echo 'True.'; //this line will run if the statement is true.
else
    echo 'False'; //only this line will run if the statement is false.
echo 'Something else'; //this line will run no matter what, but only once.
Enstage
  • 2,106
  • 13
  • 20