I have the following php code that gives me an unexpected result:
$foo = NULL; switch($foo) { case 0: print "What?!"; }
I'd expect the result to be nothing, but it matches case 0. The php manual says that NULL is a non-value, so how can it equal 0?
but for String or enum, it might be invoking equals method, which obviously needs a LHS value on which equals is being invoked. So, given no method can be invoked on a null, switch cant handle null.
PHP doesn't support this syntax. Only scalar values allowed for cases.
if / else if / else is more flexible (hence better), but switch is slightly faster because it just computes the condition once and then checks for the output, while if has to do this every time.
Switch cases should almost always have a default case. 2. To handle 'default' actions, where the cases are for special behavior.
The switch
statement applies loose comparison which means that the following things are treated as equivalent to 0:
false 0 "0" NULL "any string" ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With