Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make switch use === comparison not == comparison In PHP

Is there anyway to make it so that the following code still uses a switch and returns b not a? Thanks!

$var = 0; switch($var) {     case NULL : return 'a'; break;     default : return 'b'; break; } 

Using if statements, of course, you'd do it like this:

$var = 0; if($var === NULL) return 'a'; else return 'b'; 

But for more complex examples, this becomes verbose.

like image 225
Aaron Yodaiken Avatar asked Aug 19 '10 19:08

Aaron Yodaiken


People also ask

Does switch case use == or ===?

In answer to your question, it's === .

Can you do comparisons in a switch statement?

Use the switch statement to execute one of many code blocks based on a variable or expression's value. The switch expression is evaluated once. The comparison value will match either a statement value or trigger a default code block.

Does PHP have a switch statement?

The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed.

Is switch faster than if else PHP?

Due to the fact that "switch" does no comparison, it is slightly faster.


2 Answers

Sorry, you cannot use a === comparison in a switch statement, since according to the switch() documentation:

Note that switch/case does loose comparison.

This means you'll have to come up with a workaround. From the loose comparisons table, you could make use of the fact that NULL == "0" is false by type casting:

<?php $var = 0; switch((string)$var)  {     case "" : echo 'a'; break; // This tests for NULL or empty string        default : echo 'b'; break; // Everything else, including zero } // Output: 'b' ?> 

Live Demo

like image 110
Peter Ajtai Avatar answered Oct 13 '22 07:10

Peter Ajtai


Here is your original code in a "strict" switch statement:

switch(true) {     case $var === null:         return 'a';     default:         return 'b'; } 

This can also handle more complex switch statement like this:

switch(true) {     case $var === null:         return 'a';     case $var === 4:     case $var === 'foobar':         return 'b';     default:         return 'c'; } 
like image 32
thespacecamel Avatar answered Oct 13 '22 09:10

thespacecamel