Reputation: 2290
I created a switch statement to handle three different cases and return a result. The switch statement always fired on the first case, despite it being false. When I created an if/else statement, it works as expected. Why is this? (keep in mind that I do not use both the switch and if/else at the same time, I only have them both uncommented to show my example)
Here is the function that I am working with:
public static function statuses($statusId = null)
{
$statuses = [
1 => 'Choose Vendor',
2 => 'Approve Quote',
3 => 'Waiting on Forecast',
4 => 'Waiting on Sign Approval',
5 => 'Waiting on Final Approval',
6 => 'Waiting on Review',
7 => 'Completed'
];
// This works as expected...
if (is_numeric($statusId)) {
return $statuses[$statusId];
} elseif (is_string($statusId)) {
return array_search($statusId, $statuses);
} else {
return $statuses;
}
// This does not work as expected
switch ($statusId) {
case is_numeric($statusId):
// This always fires and the result is FALSE
var_dump(is_numeric($statusId));
return $statuses[$statusId];
case is_string($statusId):
return array_search($statusId, $statuses);
default:
return $statuses;
}
}
And here is how I am calling the method:
SignVendorJob::statuses()
Which should return the array since I am not passing an argument.
Upvotes: 1
Views: 75
Reputation: 2314
Switch statement should be like this:
switch (true) {
case is_numeric($statusId):
// This always fires and the result is FALSE
var_dump(is_numeric($statusId));
return $statuses[$statusId];
case is_string($statusId):
return array_search($statusId, $statuses);
default:
return $statuses;
}
Notice the change after switch
.
In your example the following conditions are tested in the cases:
$statusId == is_numeric($statusId)
and $statusId == is_string($statusId)
These will give wrong results.
Upvotes: 2