Logical operators in PHP

Posted on Friday, April 3rd, 2009 under , ,

Early in his career, every PHP programmer writes code like:

mysql_query( $sql ) or die( mysql_error() );

Come on! We’ve all been there. Of course, now we all agree that that’s lame and stupid and we use PDO or even ActiveRecord, but back in the days, that was widely used. What does that mean, actually? or die()?

It’s an optimization originally implemented in – I think – gone wild.

For instance, if you have a condition like:

if ( ( $a == $b ) || ( $c == $d ) ) { /* whatever */}

…if the the result in the first set of parenthesis evaluates to true, the second one isn’t evaluated because its result is irrelevant in this context. The parser already knows the answer, as “true or anything” always equals true.

The mysql_query() function returns a value that can be evaluated from a boolean point of view. If that result is evaluated to true (the query was okay), then the die() part gets left out. If the query fails and mysql_query() returns something that evaluates as false, then the die() call gets executed. That’s all, in a nutshell.

The above code could have been rewritten as:

if ( ! mysql_query( $sql ) ) {
    die( mysql_error() );
}

Still lame, but with improved readability.

Of course, you can do nifty tricks with this kind of constructs:

is_numeric ( $_GET['id'] ) || redirect( '/my/error/url' );

Cool!

Related posts

6 Responses to “Logical operators in PHP”

  1. Radu

    I really like short-circuit logic! :D

  2. Tudor

    Yep. But if you’re using juniors on the project, they may react unexpectedly to the sight of this code.

  3. Radu

    It depends. If they have basic boolean algebra knowledge, they might not be confused by that code. But then again, some of them have problems, as you mentioned in one of your previous posts, with the ++/– operators. >:)

  4. Tudor

    Dude, I’ve seen so called “seniors programmers” having these kind of flaws…

  5. Ionut G. Stan

    There are some guys using some other trick, which may be useful sometimes. Personally, I’ve never used it.

    $logged = true;
    $logged and print "Welcome";
  6. Tudor

    Yeap, but it relies on the same thing…

Leave a Reply