In PHP, how is variable scope handled in switch statements?
For instance, take this hypothetical example:
$someVariable = 0;
switch($something) {
case 1:
$someVariable = 1;
break;
case 2:
$someVariable = 2;
break;
}
echo $someVariable;
Would this print 0 or 1/2?
The variable will be the same in your whole portion of code : there is not variable scope “per block” in PHP.
So, if
$somethingis1or2, so you enter in one of thecaseof theswitch, your code would output 1 or 2.On the other hand, if
$somethingis not1nor2(for instance, if it’s considered as0, which is the case with the code you posted, as it’s not initialized to anything), you will not enter in any of thecaseblock ; and the code will output0.