note 114866 added to language.operators.logical
| From: | void at informance dot info | Date: | Wed, 16 Apr 2014 22:53:42 +0000 |
| Subject: | note 114866 added to language.operators.logical | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199284@lists.php.net to get a copy of this message | ||
To assign default value in variable assignation, the simpliest solution to me is:
<?php
$v = my_function() or $v = "default";
?>
It works because, first, $v is assigned the return value from my_function(), then this value is
evaluated as a part of a logical operation:
* if the left side is false, null, 0, or an empty string, the right side must be evaluated and,
again, because 'or' has low precedence, $v is assigned the string "default"
* if the left side is none of the previously mentioned values, the logical operation ends and $v
keeps the return value from my_function()
This is almost the same as the solution from [phpnet at zc dot webhop dot net], except that his
solution (parenthesis and double pipe) doesn't take advantage of the "or" low
precedence.
NOTE: "" (the empty string) is evaluated as a FALSE logical operand, so make sure that the
empty string is not an acceptable value from my_function(). If you need to consider the empty string
as an acceptable return value, you must go the classical "if" way.
----
Server IP: 72.52.91.14
Probable Submitter: 82.242.139.60
----
Manual Page -- http://php.net/manual/en/language.operators.logical.php
Edit -- https://master.php.net/note/edit/114866
Del: integrated -- https://master.php.net/note/delete/114866/integrated
Del: useless -- https://master.php.net/note/delete/114866/useless
Del: bad code -- https://master.php.net/note/delete/114866/bad+code
Del: spam -- https://master.php.net/note/delete/114866/spam
Del: non-english -- https://master.php.net/note/delete/114866/non-english
Del: in docs -- https://master.php.net/note/delete/114866/in+docs
Del: other reasons-- https://master.php.net/note/delete/114866
Reject -- https://master.php.net/note/reject/114866
Search -- https://master.php.net/manage/user-notes.php