note 65825 added to control-structures.switch

From: Date: Mon, 08 May 2006 14:51:14 +0000
Subject: note 65825 added to control-structures.switch
Groups: php.notes 
Request: Send a blank email to php-notes+get-110870@lists.php.net to get a copy of this message
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 ---- Server IP: 85.116.0.130 Probable Submitter: 81.178.13.93 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/control-structures.switch.php Edit -- http://master.php.net/note/edit/65825 Del: integrated -- http://master.php.net/note/delete/65825/integrated Del: useless -- http://master.php.net/note/delete/65825/useless Del: bad code -- http://master.php.net/note/delete/65825/bad+code Del: spam -- http://master.php.net/note/delete/65825/spam Del: non-english -- http://master.php.net/note/delete/65825/non-english Del: in docs -- http://master.php.net/note/delete/65825/in+docs Del: other reasons-- http://master.php.net/note/delete/65825 Reject -- http://master.php.net/note/reject/65825 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#110870) next »