Skip to content
Advertisement

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?

Advertisement

Answer

Yes, you can do

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

   case $var === FALSE:
   break;

   case $var === NULL:
   break;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement