Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php null value confusion in switch statement

Tags:

php

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?

like image 850
lang2 Avatar asked Aug 17 '11 10:08

lang2


People also ask

Can Switch case be null?

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.

Can we use condition in switch case PHP?

PHP doesn't support this syntax. Only scalar values allowed for cases.

Is switch faster than if else PHP?

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.

Is default mandatory in switch case PHP?

Switch cases should almost always have a default case. 2. To handle 'default' actions, where the cases are for special behavior.


1 Answers

The switch statement applies loose comparison which means that the following things are treated as equivalent to 0:

false 0 "0" NULL "any string" "" 
like image 90
borrible Avatar answered Oct 14 '22 20:10

borrible