Question

$a = 1;
$a OR $a = 'somthing'
echo $a; //1

Why? If = have much precedence then 'OR' then why OR execute first?

Was it helpful?

Solution 2

Because if OR has higher precedence then

$a OR $a = 'somthing'

will be parsed as:

($a OR $a) = 'somthing'

that would be technically wrong because you can't assign to an expression (while programmers would like to write expression like this is coding so it should be a valid expression).

because precedence of or operator was low hence the expression $a OR $a = 'somthing' pareses as $a OR ($a = 'somthing') And according to short-circuit first operand that is $a was evaluated as true and second operand expression not evaluated and a remains 1.

Remember precedence rules derives grammar rules and hence tells how expression will be parse. But precedence is a compile-time property that tells us how expressions are structured. Evaluation is a run-time behavior that tells us how expressions are computed (hence how expressions will be evaluates can't completely determine by precedence). And PHP docs seems to say same:

Operator Precedence
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

OTHER TIPS

When you put OR between two statement, if the first one returns true, the second one never will be executed.

in this case, the first statement ( $a ) returns true ( because $a = 1 ), so the

second one ( $a = 'somthing'; ) wont be executed.

Because 1 is truthy.

What you're saying with $a OR $a = 'somthing'; is

a is true OR set it to "somthing"

. Well, a is true, so it won't be set, while the following code would do.

$a = false;
$a OR $a = 'somthing';
echo $a; //"something"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top