note 100210 deleted from control-structures.alternative-syntax by danbrown
| From: | danbrown@php.net | Date: | Fri, 01 Oct 2010 12:01:21 +0000 |
| Subject: | note 100210 deleted from control-structures.alternative-syntax by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172873@lists.php.net to get a copy of this message | ||
Note Submitter: A dot Lepe dev+php at alepe dot com
----
Sorry, my previous comment is mistaken. It should be:
You can NOT perform if/elseif/else in one line like this:
<?php
$c = "c";
echo ($c == "a") ? 1 : ($c == "b") ? 2 : ($c == "c") ? 3 : 0;
?>
If we set $c = "b" the result will be still 3. Why?
After performing several testings, the real logic behind that line would be more similar to this:
<?php
$c = "b";
$a = ($c == "a") ? 1 : ($c == "b");
//which in our case will be "true" (as it falls in the false statement).
$b = ($a) ? 2 : ($c == "c");
//which will be "2" as $a == true
$c = $b ? 3 : 0;
//as $b > 0 turns the evaluation "true" and thus the answer is 3.
?>
So in order to be able to use if/elseif/else in one line, grouping is required (as it is expected):
<?php
$c = "b";
echo ($c == "a") ? 1 : (($c == "b") ? 2 : (($c == "c") ? 3 : 0));
//result: 2
?>