Muntasir Muntasir - 2 months ago 10
PHP Question

Does PHP have short-circuit evaluation?

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 checks later conditions like the
up_to_length($string)
? If so, then why does it do extra work when it doesn't have to?

Answer

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';
}