note 44437 added to language.operators
| From: | abodeman at yahoo dot php dot net | Date: | Thu, 05 Aug 2004 17:18:21 +0000 |
| Subject: | note 44437 added to language.operators | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-74030@lists.php.net to get a copy of this message | ||
I just spent about half an hour trying to debug a PHP script that wasn't working. The reason
that it wasn't working was that in PHP, unlike EVERY OTHER LANGUAGE that has the ternary ?:
operator, ?: is left-associative.
My code was along the lines of this:
<?php
echo ($submitted_value != '' ? $submitted_value :
$default_value != '' ? $default_value :
'no value');
?>
The idea of this code is that if $submitted_value contains something, then display that; otherwise,
if $default_value contains something, then display that; otherwise, display "no value".
However, due to PHP's strange quirk of making ?: left-associative, the code was acting like
this (note the explicit parentheses):
<?php
echo (($submitted_value != '' ? $submitted_value :
$default_value != '') ? $default_value :
'no value');
?>
So it took the result of the first ?: and used it as the condition for the second ?:. Thus, if
$submitted_value contains something, then the condition for the second ?: will be $submitted_value,
which will be true; if $submitted_value doesn't contain anything, then the condition for the
second ?: will be whether or not $default_value contains anything. So if $submitted_value contains
something, or if $submitted_value contains nothing and $default_value contains something,
$default_value gets printed; otherwise you get "no value". $submitted_value will never be
produced.
----
Manual Page -- http://www.php.net/manual/en/language.operators.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44437
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44437&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44437&report=yes
Search -- http://master.php.net/manage/user-notes.php