PHP || and && logical optimization

I'm a bit of an optimizer (at least by my definition), and this question has been listening to me for quite some time.

I am wondering if PHP does some optimization on && and ||: Take the following example:

$a = "apple"; $b = "orange"; if ($a == "orange" && $b == "orange") { //do stuff } 

When this code is executed, it checks to see if $ a is "orange". In this case, this is not so. However, there is an && operator. Since the first part ($ a == "orange") already returned false, will PHP still check if $ b is "orange?"

I have the same question for ||:

 $a = "orange"; $b = "orange"; if ($a == "orange" || $b == "orange") { //do stuff } 

When it checks if $ a is "orange", it returns true. Since this would do || return true statement, PHP will even check the second part || (since we already know that this will be true)?

I hope I have a point here, and I hope someone has an answer for me. Thanks!

+6
source share
2 answers

PHP uses a short circuit assessment with binary conditional expressions (for example, && , || or their constant equivalents), therefore, if the result of the LHS evaluation means that RHS is not required, it will not.

For instance...

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

... is an exploitation of this fact. RHS will only be evaluated if the LHS returns a true value in this example. The logic here makes sense, since you only want to call the method if it exists (until you use __call() , but that's a different story).

You can also use OR similar way.

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

This pattern is often used as the first line in PHP files that should be included and not directly accessible. If the BASE_PATH constant BASE_PATH not exist, LHS is false, so it executes the RHS, which die() script.

+6
source

Yes, PHP shorts the && and || , which means that no, the right operand will not be evaluated if the value of the left operand means that it does not need to be evaluated. There is no need to optimize them. You can check it as follows:

 function one() { echo "One"; return false; } function two() { echo "Two"; return true; } one() && two(); // Outputs One echo "\n"; two() || one(); // Outputs Two 

Here is a demo. If there were no short circuit, you would get:

 OneTwo TwoOne 
+1
source

Source: https://habr.com/ru/post/912673/


All Articles