Short Circuit Evaluation
To make PHP more efficient, a shortcut is sometimes taken in evaluating a conditional. This never changes the outcome of the condition’s evaluation, but it might keep things from happening that you might expect to happen.
The shortcut is called short circuit evaluation. This occurs when PHP decides there’s no need for it to evaluate any more of the condition because it already knows the outcome. This happens when
The first part of a condition with and in it evaluates to false, because both values in such a condition must evaluate to true.If one evaluates to false, PHP knows the condition can’t possibly evaluate to true.
The first part of a condition with or in it evaluates to true, because only one value in such a condition must evaluate to true.So, if the first evaluates to true, it doesn’t matter if the second is true or false; the condition as a whole will be true.
The problem this presents is if you use if statements with assignments or calls to functions in them. For example, an assignment returns the value that was being assigned. This is often used to assign a value and check to see if it evaluates to true or false as a Boolean at the same time. However, if the assignment appears in the second part of the conditional and the first part causes the rest to be skipped, the assignment will never take place.
Therefore, the following example script produces no output:
<?php
/* ch06ex07 – shows no output because of short circuit evaluation */
if (true || $intVal = 5) // short circuits after true
{
echo $intVal; // will be empty because the assignment never took place
}
?>
This program outputs nothing because the assignment of $intVal never takes place, so although the echo statement is executed, $intVal is empty and nothing is outputted.
Short circuit evaluation can also have an effect on calls to functions that change the value of a variable. This is for the same reason that causes assignments to be skipped. Therefore, it’s always recommended that assignments and calls to functions, which change variables, be placed outside of conditionals; if the value the function returns is needed in the conditional, store it in a variable first and put the variable in the conditional.