PHP || and && logical optimization

logic, optimization, performance, php

Solution

PHP uses short circuit evaluation with binary conditionals (such as `&&`, `||` or their constant equivalents), so if the result of evaluating the LHS means the RHS isn't necessary, it won't.

For example...

method_exists($obj, 'func') AND $obj->func();

...is an exploitation of this fact. The RHS will only be evaluated if the LHS returns a truthy value in this example. The logic makes sense here, as you only want to call a method if it exists (so long as you're not using `__call()`, but that's another story).

You can also use `OR` in a similar fashion.

defined('BASE_PATH') OR die('Restricted access to this file.');

This pattern is used often as the first line in PHP files which are meant to be included and not accessed directly. If the `BASE_PATH` constant does not exist, the LHS is falsy so it executes the RHS, which `die()`s the script.

Problem

I'm a bit of an optimization freak (at least by my definition) and this question has been bugging me for quite a while. I'm wondering if PHP does some optimization on && and ||: Take the following example: ``` $a = "apple"; $b = "orange"; if ($a == "orange" && $b == "orange") { //do stuff } ``` When that code executes, it will check if $a is equal to "orange." In this case it isn't. However, there is an && operator. Since the first part ($a == "orange") already returned false, will PHP still check if $b is equal to "orange?" I have the same question for ||: ``` $a = "orange"; $b = "orange"; if ($a == "orange" || $b == "orange") { //do stuff } ``` When it checks if $a is equal to "orange," it returns true. Since that would make the || operator return true, will PHP even check the second part of the || (since we already know it will be true)? Hopefully I am making sense here, and hopefully somebody has an answer for me. Thank you!

Original source