Short-circuiting in PHP

Short-circuiting in PHP refers to the behavior of logical operators (&&, ||, and their shorthand equivalents and and or) where the evaluation stops as soon as the final outcome of the operation is determined. This is an optimization to avoid unnecessary computations.

This behavior only applies to logical operators (&& and ||). The bitwise operators (& and |) do not short-circuit, as they evaluate both operands regardless of the first operand’s value.

$a = false;
$b = (10 / 0); // This would normally cause a division by zero error

if ($a && $b) {
    echo "This will not run";
}
// No error occurs because $b is not evaluated due to short-circuiting
$a = true;
$b = (10 / 0); // This would normally cause a division by zero error

if ($a || $b) {
    echo "This runs fine";
}
// No error occurs because $b is not evaluated due to short-circuiting

Short-circuiting is a valuable feature for writing efficient and safe code in PHP.