note 115208 added to language.operators.logical
| From: | anatoliy at ukhvanovy dot name | Date: | Thu, 12 Jun 2014 13:41:26 +0000 |
| Subject: | note 115208 added to language.operators.logical | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199671@lists.php.net to get a copy of this message | ||
If you want to use the '||' operator to set a default value, like this:
<?php
$a = $fruit || 'apple'; //if $fruit evaluates to FALSE, then $a will be set to TRUE
(because (bool)'apple' == TRUE)
?>
instead, you have to use the '?:' operator:
<?php
$a = ($fruit ? $fruit : 'apple');//if $fruit evaluates to FALSE, then $a will be set to
'apple'
?>
But $fruit will be evaluated twice, which is not desirable. For example fruit() will be called
twice:
<?php
function fruit($confirm) {
if($confirm)
return 'banana';
}
$a = (fruit(1) ? fruit(1) : 'apple');//fruit() will be called twice!
?>
But since «since PHP 5.3, it is possible to leave out the middle part of the ternary operator»
(http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary),
now you can code like this:
<?php
$a = ($fruit ? : 'apple'); //this will evaluate $fruit only once, and if it evaluates to
FALSE, then $a will be set to 'apple'
?>
But remember that a non-empty string '0' evaluates to FALSE!
<?php
$fruit = '1';
$a = ($fruit ? : 'apple'); //this line will set $a to '1'
$fruit = '0';
$a = ($fruit ? : 'apple'); //this line will set $a to 'apple', not
'0'!
?>
----
Server IP: 72.52.91.14
Probable Submitter: 109.110.92.25
----
Manual Page -- http://php.net/manual/en/language.operators.logical.php
Edit -- https://master.php.net/note/edit/115208
Del: integrated -- https://master.php.net/note/delete/115208/integrated
Del: useless -- https://master.php.net/note/delete/115208/useless
Del: bad code -- https://master.php.net/note/delete/115208/bad+code
Del: spam -- https://master.php.net/note/delete/115208/spam
Del: non-english -- https://master.php.net/note/delete/115208/non-english
Del: in docs -- https://master.php.net/note/delete/115208/in+docs
Del: other reasons-- https://master.php.net/note/delete/115208
Reject -- https://master.php.net/note/reject/115208
Search -- https://master.php.net/manage/user-notes.php