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