Synook

Conditionals and function execution in PHP

Just an interesting thing I discovered – if you place a series of functions in a conditional with AND comparison, they are executed sequentially and as soon as one returns false the conditional is exited, without executing the others.

For example, consider this if statement:

if (function1() && function2()) { }

In this statement, first function1() is run. If it returns true, the interpreter goes on to execute function2(), but if it returns false then function2() is not called! This means that in the following case nothing will be output.

function function1() {
    return false;
}
function function2() {
    echo "Function2 was run!";
    return true;
}
if (function1() && function2()) echo "Both true";