3

A simple question that could remove the need for quite a lot of if/else statements.

If, for example, I have such a query:

if ($success1=$db->query('SELECT * FROM `foo`;') || $success2=$db->query('SELECT * FROM `bar`;')) {
   ...
}

Would it stop checking when the first query is successful or not?

AM-
  • 871
  • 1
  • 10
  • 20
  • What happened when you tried it with 2 known values? – Nanne Jul 10 '12 at 12:18
  • Yes, it will stop if the first query returns something that could be evaluated to `true` – Florent Jul 10 '12 at 12:18
  • You realise that success for each query means running without error, not whether it actually returns data or not.... but executing database queries like this is not good practise – Mark Baker Jul 10 '12 at 12:19
  • http://php.net/manual/en/language.operators.logical.php, check the first example – Habib Jul 10 '12 at 12:21
  • 1
    I'm with @MarkBaker on this: there's a whole bunch of things wrong with this. You example code fails several 'best practice' tests. You may be able to make the code shorter, but you will also be lowering your code quality. `$shorter !== $better`. – SDC Jul 10 '12 at 12:23
  • It was merely an example. My code uses an `if (!preg_match || !$var=sql_query) error(..);die();` thus if the preg_match failed I wouldn't even need the query. – AM- Jul 10 '12 at 12:29

2 Answers2

8

What you're referring to is called a short circuit. Yes php uses short circuits. With AND (&&) If the first check in the conditional fails, it never checks the second. The same applies for OR ( || ). If the first check succeeds it never looks at the second statement.

See the following post for verification: PHP short circuit lazy evaluation, where is it in the php.net manual?

An example of when this is very useful is when dividing by zero. In the first check you determine if the denominator is zero, and then in the second check you do the dividing. The order is important. If the denominator is zero it will skip the second check and will never divide by zero.

if($x != 0 && 10/$x > 3)

Community
  • 1
  • 1
Steve's a D
  • 3,801
  • 10
  • 39
  • 60
6

If the first one is true, then it will not need to check anything else in the statement so it will carry on. If not, code like this:

if(isset($var) && $var == 1)

Would never work as it would throw up a not defined error. As soon as it sees the first one is false, it stops the rest of the statement.

andy
  • 2,369
  • 2
  • 31
  • 50