Answer the question
In order to leave comments, you need to log in
PHP: Weird "or" Operator Behavior
I always thought that the "||" operators and "or" in php work the same way.
Judging by the documentation , they really should work the same, except for priorities.
However
$x = 0 || 1
and
$x = 0 or 1
actually work differently.
Code:
This code outputs:
Can anyone explain this behaviour?
<?php
function foo(){
print "foo";
return 0;
}
function bar(){
print "bar";
return 1;
}
$x = foo() or bar();
var_dump($x);
foobarint(0)
Answer the question
In order to leave comments, you need to log in
Yes, they work the same, except for the priorities. For the or operator, it is so low that it is even lower than for the assignment operator.
The author has never met such a construction, which is lying around in all sorts of FAQs at every step:
$handle = mysql_connect() or die(mysql_error());
I think it's clear that in this case it's not the result of the logical OR that needs to be put in $handle, but the connection error should be handled.
Recently, a question was considered on Habré - the comma operator . Here, among other things, the answer to your question is stated.
Certainly. In the case of OR, the second operand is not evaluated if the first is TRUE. Same with AND.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question