PHP if OR is the second part checked for true?

I know this should 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, this is the same with OR, so

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

If $ a is true, it still checks $ b

I know that this is elementary material, but I can not find the answer anywhere ... Thanks

+4
source share
5 answers

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()); 
+8
source

The evaluation of logical expressions is terminated as soon as the result is known.

logical operators

+9
source

Take a 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 () is not checked. Demo here: codepad.org

+1
source

If at least one OR operand is true, there is no need to go further and check other operands, and all this will be evaluated as true.

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

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

0
source

If you know your truth tables well, you can probably figure it out yourself. As others have said, PHP will evaluate until a result is determined. In the case of OR, only one must be true for the statement to return true. Therefore, PHP evaluates until it finds the true value. If it does not find it, the statement evaluates to false.

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

All Articles