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