0

The following code should never execute like that in any other language that I know (C, C++, C#, etc.)

<?php

$do = true;

for($i=0; $i<3; $i++) {
    if($do===true) {
        $some_variable = 666;
        echo $some_variable;
        $do = false;
    }
    if(isset($some_variable)) {
        echo $some_variable;
    }
}

Why PHP won't unset a $some_variable in next loop iteration?

Bartłomiej Sobieszek
  • 2,692
  • 2
  • 25
  • 40
  • 1
    Loops don't have their own scope in PHP. – Charlotte Dunois Nov 03 '16 at 18:10
  • 1
    Possible duplicate of [Are PHP variables declared inside a foreach loop destroyed and re-created at each iteration?](http://stackoverflow.com/questions/13626812/are-php-variables-declared-inside-a-foreach-loop-destroyed-and-re-created-at-eac) – Patrick Q Nov 03 '16 at 18:12
  • Seems like you can echo the variable outside the for loop even if you defined it inside. I think PHP treats those variables as some kind of global for the current page. The same won't apply for functions and classes tough – Phiter Nov 03 '16 at 18:15
  • Possible duplicate of [PHP for ; foreach variable scope](http://stackoverflow.com/questions/34637603/php-for-foreach-variable-scope) – Charlotte Dunois Nov 03 '16 at 18:16

2 Answers2

0

Because it is set in the global scope. Once the first iteration sets it, the variable remains set.

http://php.net/manual/en/language.variables.scope.php

Here you can move the work to a function with its own scope. After the first iteration $do is set to false, and it no longer sets the variable:

$do = true;

function do_thing() {
    global $do;
    if($do===true) {
        $some_variable = 666;
        echo $some_variable;
        $do = false;
    }
    if(isset($some_variable)) {
        echo $some_variable;
    }
}

for($i=0; $i<3; $i++) {
    do_thing();
}
mike.k
  • 3,277
  • 1
  • 12
  • 18
0

Or, you can just make sure you unset the $some_variable in the first iteration.

<?php

$do = true;

for($i=0; $i<3; $i++) {

    if($do===true) {
        $some_variable = 666;
        // echo $some_variable;
        $do = false;
    }
    if(isset($some_variable)) {
        echo $some_variable;
        unset($some_variable);
    }

}

?>

The point is that since you create the $some_variable in the first run of the loop, it will be available in all the subsequent runs of the loop, unless you specifically unset it again.

junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33