DrDamnit DrDamnit - 2 months ago 12
PHP Question

How does PHP evaluate compound if statements?

Given the nested if statements below:

if(file_exists($fullPathToSomeFile)) {
if(is_readable($fullPathToSomeFile)) {
include($fullPathToSomeFile);
}
}


how does this differ from:

if(file_exists($fullPathToSomeFile) && is_readable($fullPathToSomeFile)) {
include($fullPathToSomeFile);
}


Specifically, I want to know how PHP will treat is_readable() if $fullPathToSomeFile does not exist (first conditional fails).

At some point, I started nesting these because using the one-liner version was throwing errors under some conditions. It seems to me that using any 'and' will ask PHP to evaluate everything regardless of the true / false result.

What I really want is to have it stop evaluating when it reaches the first false, thereby preventing warnings or fatal errors when the conditional fails. Doing it nested (first example) guarantees this, but nested if statements are harder to read and maintain.

What's the current best practice for handling this?

Answer

Specifically, I want to know how PHP will treat is_readable() if $fullPathToSomeFile does not exist (first conditional fails).

PHP uses short-circuit evaluation for the && operator. That is, if the first condition in an expression like if (A && B) fails, it is obvious the the whole condition will be false. Thus, the second condition B does not need to be evaluated to determine the result and will not be evaluated at all.

Take for example the following code:

<?php
  function hey()
  {
    echo "Hey there!\n";
    return true;
  }

  if (false && hey())
  {
    echo "Statement evaluated to true.\n";
  }
  else
  {
    echo "Statement evaluated to false.\n";
  }
?>

This will echo only one line ("Statement evaluated to false."), but not "Hey there!", because the second part of the if condition will not be evaluated.