U
U
un1t2011-04-07 07:22:16
PHP
un1t, 2011-04-07 07:22:16

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

6 answer(s)
[
[email protected]><e, 2011-04-07
@barmaley_exe

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.

K
Khurshed Nurmatov, 2011-04-07
@Hoorsh

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.

F
Fastto, 2011-04-07
@Fastto

Recently, a question was considered on Habré - the comma operator . Here, among other things, the answer to your question is stated.

D
DileSoft, 2011-04-07
@DileSoft

Certainly. In the case of OR, the second operand is not evaluated if the first is TRUE. Same with AND.

H
homm, 2011-04-07
@homm

$x = (foo() or bar());

S
Sergey Beresnev, 2011-04-07
@sectus

Read and sign.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question