make switch use === comparison not == comparison In PHP
Sorry, you cannot use a ===
comparison in a switch statement, since according to the switch() documentation:
Note that switch/case does loose comparison.
This means you'll have to come up with a workaround. From the loose comparisons table, you could make use of the fact that NULL == "0"
is false by type casting:
<?php$var = 0;switch((string)$var) { case "" : echo 'a'; break; // This tests for NULL or empty string default : echo 'b'; break; // Everything else, including zero}// Output: 'b'?>
Here is your original code in a "strict" switch statement:
switch(true) { case $var === null: return 'a'; default: return 'b';}
This can also handle more complex switch statement like this:
switch(true) { case $var === null: return 'a'; case $var === 4: case $var === 'foobar': return 'b'; default: return 'c';}
Not with switch
- it only does so called "loose" comparisons. You can always replace it with a if/else if
block, using ===
.