0

I had a problem were I need to check two conditions, A and B. The thing is, checking B takes a lot of time, and if A is already false I don't need to check for B. I can easily do:

if(a)
  if(b)
    // Do something

But I wonder, if I do if(a AND b), does the PHP interpreter check for A and B and then apply the AND operator? Or does it already "know" there is an AND operator and so if A is false it does not checks for B?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DomingoSL
  • 14,920
  • 24
  • 99
  • 173

4 Answers4

2

What you are talking about is called Short-Circuit evaluation. I am not a PHP expert but a quick search on google explains that it is implemented in PHP. So, if A is false, B will not be executed.

http://en.wikipedia.org/wiki/Short-circuit_evaluation

justanotherdev
  • 112
  • 1
  • 7
1

You can use "lazy evaluation" like this:

if (A && B) {
   //do shomething..
}

The "B" expression will evaluate only when the "A" expression is true.

Angelo Giuffredi
  • 923
  • 3
  • 13
  • 26
0

Depends on the language. PHP Will stop evaluating as soon as it knows the result will be false which means you can do...

if($connection->connected() and $connection->doSomething()) {

}

It will on do doSomething() if it's connected.

Basic
  • 26,321
  • 24
  • 115
  • 201
0

it already "knows" there is and AND operator and so if A is false it does not checks for B.

Actually this concept is known as short-circuiting in programming languages. PHP supports short circuiting. This means according to the nature of the operator php will avoid checking the other variable (to avoid additional overhead).

AND example if(a AND b) so if a is false php won't check b at all because anything AND false is false.

OR example if(a OR b) so if a is true php won't check or evaluate b because true OR true is true , true OR false is true as well.

sp3tsnaz
  • 506
  • 7
  • 16