note 65825 deleted from control-structures.switch by bjori
| From: | bjori@php.net | Date: | Mon, 08 May 2006 15:22:33 +0000 |
| Subject: | note 65825 deleted from control-structures.switch by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-110871@lists.php.net to get a copy of this message | ||
Note Submitter: php dot danson at spamgourmet dot com
Reason: in docs
----
Watch out if your switch value is empty! If it is, it can invert the result of an expression that
returns 'false'.
Example:
<?php
switch ($domain){
case "greentheme.net": $theme = "green";
break;
case (strpos($domain,"-secure.com")!==FALSE): $theme = "gold";
break;
default: $theme = "white";
break;
}
?>
This block takes a domain and determines the theme to use. If the domain matches greentheme.net it
uses the green theme. If the domain contains "-secure.com" in it it uses the gold theme.
Otherwise it uses the white theme.
Now what happesn if $domain is blank ("")?
1. strpos("","-secure.com") evaluates to FALSE
2. FALSE !== FALSE evalues to FALSE
3. So you would think that this case is skipped.
HOWEVER an additional step is taken! Remember that a switch statement compares the case values to
the switch value.
Thus it compares:
4. $domain == FALSE
aka "" == FALSE
which in PHP evaluates to TRUE!
Thus the case block is indeed executed and the gold theme is used when the white should have.
Simple solution:
Make sure empty variables (or variables that evaluate to false) are never passed into a switch!
Dan