phplazy-evaluationevaluation

Does php evaluate the second argument of an or statement if the first evaluates to false?


So my question is about the behaviour of php in the case of an or statement taking two functions. When the first function already evaluates to true, is there a chance that the second function will still be executed?

I hope that the following code can clarify what I mean:

$dbh->startTransaction();

$stmt = $dbh->prepare("DELETE FROM foo WHERE id=:id");

$stmt->bindParam(':id', $id, PDO::PARAM_INT);

if (!$stmt->execute() || !bar($id)) {
    $dbh->rollBack();
}

What I want to be sure of is that bar() is never called when $stmt fails to execute.

I know that in some languages the or statement would return true the moment !$stmt->execute() evaluated to true and that I could be sure that bar() would not be called unless !$stmt->execute() evaluated to false (meaning $stmt->execute() evaluated to true and the query was sucessful).

Do I have this certainty in php or is it possible that the server would evaluate $stmt->execute() and bar($id) simultaneously or in the reverse order and in such a way wreak havoc on my database?

I am assuming I would be able to apply whatever answer I get here to an and statement as well. If that is not the case, please tell me.


Solution

  • The logical operator ||,or means it won't execute the second expression if the first evaluates to true. If you are using | then the second expression is going to be evaluated even if the first evaluates to true.

    if ($expression || $expression) {
        //
    }
    

    here, if the first expression evaluates to true, then || won't let the second expression to evaluate and flow continues in if block. The second expression only be evaluated when the first becomes false.

    This boolean operation is exactly as explain in major programming languages, not only in php. If you want to look in depth, please visit Logical Operators in php Doc.

    Logical Operators

    The logical operator || has left associativity as per Precedance Rules, states the left expression always evaluates first, if left fails then right will be evaluated.