Re: & and && and weird results

From: Date: Wed, 01 Apr 2009 16:45:44 +0000
Subject: Re: & and && and weird results
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-290924@lists.php.net to get a copy of this message
PJ wrote:
I hope somebody can make sense of this. First, I don't understand what the difference is supposed to be between & and && - is there a difference for php and/or mysql? Second, I am trying to select all occurrences in a table.column where the first letter of the name is I, J, or K but not I or J or K; I want the all. Now, entering the following is no problem for any one letter: SELECT * FROM book
        WHERE id IN (SELECT bookID
        FROM book_author WHERE authID IN (SELECT author.id
        FROM author
        WHERE LEFT(last_name, 1 ) = '$Auth' ));
But the following does not work: SELECT * FROM book
        WHERE id IN (SELECT bookID
        FROM book_author WHERE authID IN (SELECT author.id
        FROM author WHERE LEFT(last_name, 1 ) = '$Auth' &&
LEFT(last_name, 1 ) = '$Auth1' && LEFT(last_name, 1 ) = '$Auth2')); Yet this gives off the wall results where the last names are nowhere near what they should be. Anyone have a rational explanation? I wasn't aware that && was an option in MySQL, I've always used "AND". If there is a difference it's probably the same as in PHP and many other languages. Allow me to explain.
In the case of & the left-side expression is evaluated for true and if not true, the right side expression is not evaluated. In the case of && both sides are evaluated regardless of the value of either side. Here's an example: $a = 1; $b = 2; $result = ($a == 2) && $b++; // In this case, $a does not equal two and therefor the left-side is false, thus the right-side is never evaluated. $b remains 2. $result = ($a == 2) & $b++; // In this case, $a still does not equal two and therefor the left-side is still false, however because we use the '&' operator the right side is evaluated anyway and $b now equals 3. echo $result; // In both cases, $result is false. HTH, Kyle -- *Kyle Smith* UNIX/Linux Systems Administrator Inforonics, LLC

« previous php.general (#290924) next »