Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way in php to make SWITCH opreator compare cases strict?

I have such control structure:

switch ($var) {
   case TRUE: 
   break;

   case FALSE:
   break;

   case NULL:
   break;
}

And my NULL case is never invoked because as I found in php manual:

Note that switch/case does loose comparision.

I know I can use IF instead of SWITCH but I wouldn't like to, I have already some IF's in every CASE of my SWITCH.

Is there any way to rewrite somehow SWITCH or to use some tricks to make it compare values strict?

like image 400
Green Avatar asked May 19 '12 15:05

Green


People also ask

Does switch-case use strict comparison?

Switch cases use strict comparison (===). The values must be of the same type to match. A strict comparison can only be true if the operands are of the same type.

What is the difference between == and === comparison operators in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

How does PHP compare strings with comparison operators?

PHP will compare alpha strings using the greater than and less than comparison operators based upon alphabetical order. In the first example, ai comes before i in alphabetical order so the test of > (greater than) is false - earlier in the order is considered 'less than' rather than 'greater than'.

Can you do a comparison in a switch statement?

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String. equals method; consequently, the comparison of String objects in switch statements is case sensitive.


1 Answers

Yes, you can do

switch (true) {
   case $var === TRUE: 
   break;

   case $var === FALSE:
   break;

   case $var === NULL:
   break;
}
like image 88
Maxim Krizhanovsky Avatar answered Nov 13 '22 14:11

Maxim Krizhanovsky