I'm trying to track down why the if/else logic returns the correct datatypes versus the switch that does not.
IF/ELSE:
$value = false;
var_dump($value);
if(is_int($value)) {
echo "INT";
} elseif (is_bool($value)) {
echo "BOOL";
} elseif (is_null($value)) {
echo "NULL";
} else {
echo "DEFAULT";
}
SWITCH:
$value = false;
var_dump($value);
switch ($value) {
case is_int($value):
echo "INT";
break;
case is_bool($value):
echo "BOOL";
break;
case is_null($value):
echo "NULL";
break;
default:
echo "DEFAULT";
}
I'm not using strict comparison in the if/else. Not sure what's going on. Anyone?
If you wanted your switch statement to work .. You nee to switch (gettype($value))
-- Which checks the type of variable you have against the entire statement... then case 'boolean':
for example would check for a boolean
A literal translation of how that would look in your case is:
$value = false;
var_dump($value);
switch (gettype($value)) {
case 'integer':
echo "INT";
break;
case 'boolean':
echo "BOOL";
break;
case 'NULL':
echo "NULL";
break;
default:
echo "DEFAULT";
}
With the following types
being what you can check for:
boolean
integer
double
string
array
object
resource
NULL
unknown type
switch
compares a value to cases, this is how your code is executed
$value = FALSE;
var_dump(is_int($value)); // Gives FALSE
switch ($value) {
// PHP runs is_int first and it returns FALSE
// It becomes "case FALSE:" (Which is correct, $value is FALSE)
// So INT is printed
case is_int($value):
....
The correct way to check for a type using switch
is in @zak's answer.
When you write
switch ($variable) {
case <expression>:
...
break;
}
it's equivalent to writing:
if ($variable == <expression>) {
...
}
So your cases are analogous to writing
if ($value == is_int($value)) {
which is not the same as
if (is_int($value)) {
While I personally consider it poor form, some people like writing:
switch (true) {
case is_int($value):
...
break;
case is_bool($value):
...
break;
...
}