Serj Sagan
Serj Sagan

Reputation: 30208

PHP if OR is the second part checked on true?

I know this must be a simple question, but I know that in PHP in a statement like this

if ($a && $b) { do something }

if $a is false PHP doesn't even check $b

Well is the same thing true about OR so

if ($a || $b) { do something }

If $a is true, does it still check $b

I know this is elementary stuff, but I can't find the answer anywhere... Thanks

Upvotes: 4

Views: 360

Answers (5)

Bailey Parker
Bailey Parker

Reputation: 15905

If you know your truth tables fairly well, then you can probably figure it out yourself. As others have said, PHP will evaluate until it is certain of an outcome. In the case of OR, only one has to be true for the statement to return true. So PHP evaluates until it finds a true value. If it doesn't find one, the statement evaluates to false.

<?php
if(true && willGetCalled()) {}
if(false && wontGetCalled()) {}
if(true || wontGetCalled()) {}
if(false || willGetCalled()) {}
?>

Upvotes: 0

Nabil Kadimi
Nabil Kadimi

Reputation: 10394

If at least one OR Operand is true, there is no need to go further and check the other operands and the whole thing will evaluate to true.

(a || b || c || d || e ||...) will be TRUE if at least one of the operands is true, thus once I found one operand to be true I do not need to check the following operands.

This logic applies everywhere, PHP, JAVA, C...

Upvotes: 0

schmijos
schmijos

Reputation: 8695

Look at this example:

function foo1() {
  echo "blub1\n";
  return true;
}

function foo2() {
  echo "blub2\n";
  return false;
}

if (foo1() || foo2()) {
  echo "end.";
}

$b / foo2() isnt checked. Demo here: codepad.org

Upvotes: 1

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

See Example 1 on the Logical Operators page in the manual.

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

Upvotes: 8

Jacob
Jacob

Reputation: 43229

Evaluation of logical expressions is stopped as soon as the result is known.

logical operators

Upvotes: 9

Related Questions