Bartłomiej Sobieszek Bartłomiej Sobieszek - 28 days ago 8
PHP Question

Why PHP variables are persistent within loop cycles?

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?

Answer

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();
}
Comments