If you create a variable inside a if statement is it available outside the if statement?

In PHP, if doesn’t have its own scope. So yes, if you define something inside the if statement or inside the block, then it will be available just as if you defined it outside (assuming, of course, the code inside the block or inside the if statement gets to run).

To illustrate:

if (true)  { $a = 5; }    var_dump($a == 5);   // true

The condition evaluates to true, so the code inside the block gets run. The variable $a gets defined.

if (false) { $b = 5; }    var_dump(isset($b)); // false

The condition evaluates to false, so the code inside the block doesn’t get to run. The variable $b will not be defined.

if ($c = 5) { }           var_dump($c == 5);   // true

The code inside the condition gets to run and $c gets defined as 5 ($c = 5). Even though the assignment happens inside the if statement, the value does survive outside, because if has no scope. Same thing happens with for, just like in, for example, for ($i = 0, $i < 5; ++$i). The $i will survive outside the for loop, because for has no scope either.

if (false && $d = 5) { }  var_dump(isset($d)); // false

false short circuits and the execution does not arrive at $d = 5, so the $d variable will not be defined.

For more about the PHP scope, read the variable scope manual page.

Leave a Comment