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?
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.
== 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.
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'.
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.
Yes, you can do
switch (true) {
case $var === TRUE:
break;
case $var === FALSE:
break;
case $var === NULL:
break;
}
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