Re: & and && and weird results

From: Date: Wed, 01 Apr 2009 18:06:12 +0000
Subject: Re: & and && and weird results
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-290927@lists.php.net to get a copy of this message
Kyle Smith wrote: > Kyle Smith wrote: >> 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 >> >> > Oops, my first paragraph is backwards. I'm sure that was confusing! > My example is the correct logic for && and &, and the paragraph before > that is exactly wrong. > Not really clear... I thought that $b+ would == 3 ; why two + ? But this does not explain the weir results I am getting; and BTW, if I use AND does not work either. What am I supposed to use to get the results I am looking for? -- unheralded genius: "A clean desk is the sign of a dull mind. " ------------------------------------------------------------- Phil Jourdan --- pj@ptahhotep.com http://www.ptahhotep.com http://www.chiccantine.com/andypantry.php

« previous php.general (#290927) next »