One of the things I like the most of JavaScript is that the logical operators are very powerful:
&&
can be used to safely extract the value of an object's field, and will return null if either the object or the field has not been initialized
// returns null if param, param.object or param.object.field
// have not been set
field = param && param.object && param.object.field;
||
can be used to set default values:
// set param to its default value
param = param || defaultValue;
Does PHP allow this use of the logical operators as well?
Logical data is data that has been converted to a logical format for use in logical operations. There are three values that logical data can have: TRUE, FALSE, or NULL. Three types of data—numeric data, string data, and the null value—can function as logical data.
Logical OperatorsIt returns TRUE if both of the arguments evaluate to TRUE. This operator supports short-circuit evaluation, which means that if the first argument is FALSE the second is never evaluated. | | is the logical or operator. It returns TRUE if either argument evaluates to TRUE.
Logical Operators are used to perform logical operations and include AND, OR, or NOT. Boolean Operators include AND, OR, XOR, or NOT and can have one of two values, true or false.
'and' and '&&' is the same operator, apart from precedence differences. They are different operators, but they operate the same, apart from precedence differences. also, using '&&' makes you look cooler.
PHP returns true
orfalse
. But you can emulate JavaScript's r = a || b || c
with:
$r = $a ?: $b ?: $c;
Regarding 'ands', something like:
$r = ($a && $a->foo) ? $a->foo->bar : null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With