Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP syntax surprise with conditional operator "?:" and "OR"

Today, I was open-mouthed by the following:

$asdf = ((1 OR true) ? "asdf" : "fdsa");
var_dump($asdf); // print "asdf"

$asdf = (1 OR true) ? "asdf" : "fdsa";
var_dump($asdf); // print "asdf"

$asdf = (1 OR true ? "asdf" : "fdsa");
var_dump($asdf); // print true

$asdf = 1 OR true ? "asdf" : "fdsa";
var_dump($asdf); // print 1

Ok, the last does not surprise me much, but the third? Can anyone explain?

like image 917
Stefano Avatar asked Aug 14 '15 07:08

Stefano


People also ask

What is -> called in PHP?

The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

What is conditional operator in PHP?

ternary operator: The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right.

What is the format of conditional operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Is there ternary operator in PHP?

The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.


1 Answers

This is all about operator precedence and their associativity

http://php.net/manual/en/language.operators.precedence.php

or has lower precendence than = that is why it will be executed first

so $asdf = 1 OR true ? "asdf" : "fdsa";

will be someting like

($asdf = 1) or true ? :"asdf" : "fdsa" that is why it will print 1.

$a or $b check whether $a or $b is true if $a is true then it is returned and it does not even go to check $b

In third case

$asdf = (1 OR true ? "asdf" : "fdsa");

() has higher precedence than = so it will be executed before assignment.

To prove it

change OR to || which has higher precendence than =

$asdf = 1 || true ? "asdf" : "fdsa";

var_dump($asdf); // print asdf
like image 148
Robert Avatar answered Oct 18 '22 17:10

Robert