Is there anyway to make it so that the following code still uses a switch and returns b
not a
? Thanks!
$var = 0;
switch($var) {
Nope. From the manual page:
Note that switch/case does loose comparison.
If you only have two conditions, use an if
like your second example. Otherwise, check for NULL
first and switch on the other possibilities:
if (is_null($var))
{
return 'a';
}
switch ($var)
{
// ...
}
If you want to test both value and type of your variable, then build a new string variable containing both informations and compare it with your different scenarios (by concatenation) it should work for your case if you implement all possible types (according to gettype() documentation), example :
<?php
$var= 9999;
$valueAndTypeOfVar = (string)$var.' '.gettype($var);
switch($valueAndTypeOfVar) {
case "$var boolean" : echo 'a'; break;
case "$var integer" : echo 'b'; break;
case "$var double" : echo 'c'; break;
case "$var string" : echo 'd'; break;
case "$var array" : echo 'e'; break;
case "$var object" : echo 'f'; break;
case "$var resource" : echo 'g'; break;
case "$var NULL" : echo 'h'; break;
case "$var unknown type" : echo 'i'; break;
default: echo 'j'; break;
}
// Outputs: 'b'
?>
Not with switch
- it only does so called "loose" comparisons. You can always replace it with a if/else if
block, using ===
.
I had the same problem in a switch with string containing numbers ("15.2" is equal to "15.20" in a switch for php)
I solved the problem adding a letter before the text to compare
$var = '15.20';
switch ('#'.$var) {
case '#15.2' :
echo 'wrong';
break;
case '#15.20' :
echo 'right';
break;
}
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'
?>
Live Demo
You can also switch on the type of the variable:
switch (gettype($var)) {
...
}