note 92635 modified in control-structures.switch by felipe
| From: | felipe@php.net | Date: | Sun, 02 Aug 2009 15:38:57 +0000 |
| Subject: | note 92635 modified in control-structures.switch by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-159009@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.
<?php
$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:
<?php
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!
--was--
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!
http://php.net/manual/en/control-structures.switch.php