note 92635 added to control-structures.switch

From: Date: Sat, 01 Aug 2009 14:48:08 +0000
Subject: note 92635 added to control-structures.switch
Groups: php.notes 
Request: Send a blank email to php-notes+get-158986@lists.php.net to get a copy of this message
Again, just to re-iterate, if you supply 0 as the switched element, only the first statement will run if the comparison is with text. $in = array('first',0,"second"); foreach ($in as $a){ switch ($a){ case "first": print "first<br>"; break; case "second": print "second<br>"; break; } } This is annoying if you're using an array where you've got key's which could be text or numbers, so I'm using the suggested idea of: switch (true){ case ($a==="first"): print "first<br>"; break; case ($a==="second"): print "second<br>"; break; } The reason for this as mentioned on http://uk3.php.net/ternary is that: "If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement." Effectively it's saying if ($a=="first") which becomes does ($a (0) == 0) which is yes. In my example this mean't a date had a regular expression of an email applied to it which didnt help! ---- Server IP: 64.71.164.2 Probable Submitter: 87.82.12.35 ---- Manual Page -- http://www.php.net/manual/en/control-structures.switch.php Edit -- https://master.php.net/note/edit/92635 Del: integrated -- https://master.php.net/note/delete/92635/integrated Del: useless -- https://master.php.net/note/delete/92635/useless Del: bad code -- https://master.php.net/note/delete/92635/bad+code Del: spam -- https://master.php.net/note/delete/92635/spam Del: non-english -- https://master.php.net/note/delete/92635/non-english Del: in docs -- https://master.php.net/note/delete/92635/in+docs Del: other reasons-- https://master.php.net/note/delete/92635 Reject -- https://master.php.net/note/reject/92635 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158986) next »