note 44437 deleted from language.operators by tularis

From: Date: Tue, 12 Oct 2004 14:04:56 +0000
Subject: note 44437 deleted from language.operators by tularis
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-78417@lists.php.net to get a copy of this message
Note Submitter: abodeman@yahoo ---- 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.

« previous php.notes (#78417) next »