note 49188 added to control-structures.switch
| From: | rdoggett at oz dot net | Date: | Wed, 19 Jan 2005 13:01:57 +0000 |
| Subject: | note 49188 added to control-structures.switch | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-83622@lists.php.net to get a copy of this message | ||
Here's an often overlooked way of doing (nearly) the same thing:
<?php
echo ($i == 0) ? "i is zero" :
(($i == 1) ? "i equals 1" :
(($i == 2) ? "i equals 2" : ""));
?>
This may be an idiomatic surprise at first. But the clean and concise code speaks for itself.
Beware; PHP seems to parse the ternary operator with a different precedence than other languages
such as C or perl or javascript. This means PHP requires nested parenthesis around each nested
group to avoid unexpected results. Even so, this construct is still very understandable and
maintainable, compared to the equivalent switch or if statements.
----
Manual Page -- http://www.php.net/manual/en/control-structures.switch.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+49188
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49188&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49188&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49188&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49188&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49188&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+49188&report=yes
Search -- http://master.php.net/manage/user-notes.php