note 74253 added to control-structures.alternative-syntax
| From: | geekmanatTextbookTorrentsdotcom at osu1 dot php dot net | Date: | Sun, 01 Apr 2007 10:09:59 +0000 |
| Subject: | note 74253 added to control-structures.alternative-syntax | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125002@lists.php.net to get a copy of this message | ||
The bug in your example is user error.
<?
$foobar = 2;
echo 'Foobar is ' . ($foobar == 2) ? 'foo' : 'bar';
// outputs 'foo';
echo 'Foobar is ' . (($foobar == 2) ? 'foo' : 'bar');
// outputs 'Foobar is foo';
?>
When using the ? : operators you should always wrap the entire thing in parentheses to avoid the
problem you describe. By my understanding, the issue an extension of your example:
<?
$pet-type = 1;
$pet-name = 'Mittens';
echo 'My ' . ($pet-type == 1) ? 'cat' : 'puppy' . 'dog' .
'\'s name is ' . $pet-name . '.';
// returns 'cat'
echo 'My ' . (($pet-type == 1) ? 'cat' : 'puppy' . 'dog') .
'\'s name is ' . $pet-name . '.';
// returns 'My cat\'s name is Mittens.'
?>
You see that without parentheses the parser has no way of differentiating between the false case and
the rest of the string.
----
Server IP: 66.207.199.35
Probable Submitter: 67.70.104.209
----
Manual Page -- http://www.php.net/manual/en/control-structures.alternative-syntax.php
Edit -- https://master.php.net/note/edit/74253
Del: integrated -- https://master.php.net/note/delete/74253/integrated
Del: useless -- https://master.php.net/note/delete/74253/useless
Del: bad code -- https://master.php.net/note/delete/74253/bad+code
Del: spam -- https://master.php.net/note/delete/74253/spam
Del: non-english -- https://master.php.net/note/delete/74253/non-english
Del: in docs -- https://master.php.net/note/delete/74253/in+docs
Del: other reasons-- https://master.php.net/note/delete/74253
Reject -- https://master.php.net/note/reject/74253
Search -- https://master.php.net/manage/user-notes.php