How can I make the switch respect data types ( is there a workaround better then if/else ) ?
Bare in mind that you're asking PHP to juggle types.
If you see the PHP type comparison table you'll see that, for example, null
and ''
are loosly equivalent, ie null == ''
.
in php.net manual it is a
note: Note that switch/case does loose comparision.
"loose comparison" means that switch won't check the type.
switch will only compare values:
<?php
if('a string' == 0) echo 'a string is 0' . PHP_EOL;
if('a string' === 0) echo 'but you will never see this' . PHP_EOL;
switch(0){
case 'a string': echo 'a string' . PHP_EOL;
case 'another string': echo 'another string' . PHP_EOL;
}
if('a string' == true) echo 'a string is TRUE' . PHP_EOL;
if('a string' === true) echo 'but you will never see this' . PHP_EOL;
switch(true){
case 'a string': echo 'a string' . PHP_EOL;
case 'another string': echo 'another string' . PHP_EOL;
}
?>
will output:
a string is 0
a string
another string
a string is TRUE
a string
another string
switch (true) {
case $value === '0' :
echo 'zero';
break;
case $value === '' :
echo 'empty';
break;
case $value === null :
echo 'null';
break;
case $value === false :
echo 'false';
break;
default :
echo 'default';
break;
}
I think, it's more readable than a if-elseif
-chain like given below:
if ($value === '0') {
echo 'zero';
} else if ($value === '') {
echo 'empty';
} else if ($value === null) {
echo 'null';
} else if ($value === false) {
echo 'false';
} else {
echo 'default';
}
i believe you can try if-then to facilitate the use of '===' instead:
<?php
$value = 0;
if ($value==="") {
echo "blank (string)";
}
else
if ($value==="0") {
echo "zero (string)";
}
else
if ($value===false) {
echo "false (boolean)";
}
else
if ($value===null) {
echo "null (object)";
}
else
if ($value===0) {
echo "zero (number)";
}
else {
echo "other";
}
?>
another option, depending on what you like to look at:
switch($foo ?: strtoupper(gettype($foo))){
case 'bar':
case 'bork':
echo $foo;
break;
case 'NULL': // $foo === null
echo 'null';
break;
case 'INTEGER': // $foo === 0
echo 'zero';
break;
case 'ARRAY': // $foo === array()
echo 'array';
break;
case 'STRING': // $foo === ''
echo 'empty';
break;
case 'BOOLEAN': // $foo === false
echo 'false';
break;
default:
echo $foo;
break;
}
depending on your data, you could include an underscore for added clarity, like '_NULL', but it's not as clean IMO.
personally, I concur with the accepted answer for something like a quick null check:
case $foo === null: