Does PHP have short-circuit evaluation?

05/04/2020 01:00:02

Given the following code:

if (is_valid($string) && up_to_length($string) && file_exists($file)) 

If is_valid($string) returns false, does the php interpreter still check later conditions, like up_to_length($string)?
If so, then why does it do extra work when it doesn't have to?

Verified Answer (94 Votes)

04/17/2011 21:28:07

Yes, the PHP interpreter is "lazy", meaning it will do the minimum number of comparisons possible to evaluate conditions.

If you want to verify that, try this:

function saySomething()
    echo 'hi!';
    return true;

if (false && saySomething())
    echo 'statement evaluated to true';

Answer #2 (9 Votes)

03/09/2017 09:27:15

Yes, it does. Here's a little trick that relies on short-circuit evaluation. Sometimes you might have a small if statement that you'd prefer to write as a ternary, e.g.:

    if ($confirmed) {
        $answer = 'Yes';
    } else {
        $answer = 'No';

Can be re-written as:

   $answer = $confirmed ? 'Yes' : 'No';

But then what if the yes block also required some function to be run?

    if ($confirmed) {

        $answer = 'Yes';
    } else {
        $answer = 'No';

Well, rewriting as ternary is still possible, because of short-circuit evaluation:

    $answer = $confirmed && (do_something() || true) ? 'Yes' : 'No';

In this case the expression (do_something() || true) does nothing to alter the overall outcome of the ternary, but ensures that the ternary condition stays true, ignoring the return value of do_something().


Answer #3 (7 Votes)

01/24/2017 16:04:23

Bitwise operators are & and |. They always evaluate both operands.

Logical operators are AND, OR, &&, and ||.

  • All four operators only evaluate the right side if they need to.
  • AND and OR have lower precedence than && and ||. See example below.


From the PHP manual:

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;

In this example, e will be true and f will be false.

Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.