Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do PHP's logical operators work as JavaScript's?

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?

like image 712
pyon Avatar asked Mar 11 '11 21:03

pyon


People also ask

What kinds of values do logical operators work with?

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.

What does a logical operator evaluate to?

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.

What is the role of logical operators?

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.

Are the operators && and and interchangeable?

'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.


1 Answers

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;
like image 82
Matthew Avatar answered Sep 23 '22 04:09

Matthew