In javascript the logical or-operator returns the first truthy operand, e.g.
var x = null || 5 || 1;
assigns 5 to x.
Is there somthing similar for php?
In javascript the logical or-operator returns the first truthy operand, e.g.
var x = null || 5 || 1;
assigns 5 to x.
Is there somthing similar for php?
The use case you describe is: if the value exists use it, otherwise use a default value. This is a pretty common pattern.
As of PHP 5.3 you can do:
$var = $foo ?: 5;
In older versions you can do:
$var = $foo ? $foo : 5;
Note that in:
var x = null || 5 || 1;
the final path || 1
will never get chosen because 5
is never falsy.
||
is a logical operator in PHP and many other programming languages. Learn more about logical operators in the official PHP documentation.
What you are searching for is a ternary operator, which is the following in PHP:
$valueOne = $null ? $null : $five;
Since PHP 5.3 you may use the short form:
$valueOne = $null ?: $five;
And since its associativity is left
you may use it multiple times successively:
$valueOne = $null ?: $five ?: $one;