'if' performance question

Hey,

Between the two, which one is recommended performance/better code wise?


	if ( ( file_exists($some_file) ) && ( ($license == 'valid') || ($license = 'expired') ) ) {
		// do nothing
	} else {
                echo 'alert';
	}


	if ( !file_exists($some_file) ) {
		echo 'alert';
	} else {
		if( ($license == 'valid') || ($license = 'expired') ) {
		// do nothing
		} else {
			echo 'alert';
		}
	}

Thanks!

Hi zurih,

There are two things worth knowing about how PHP evaluates logical statements.

  1. It evaluates the conditions left to right (as you might expect), and
  2. It stops evaluating the conditions once it knows enough to pass or fail the statement.

So looking at your first example, it evaluates file_exists($some_file). Next is the AND (&&) operator, so if the first condition evaluates to false, PHP won’t bother evaluating the rest of the conditions.

It’s also worth considering that combining the checks into a single IF statement avoids nesting and makes your code easier to read, which is often a more important consideration than micro-optimisation.

Thank you!