Page 1 of 1

Using || and OR, seems like bug...

Posted: Sat May 13, 2006 11:32 am
by Randy789
Hi, I've searched and looked in the PHP.net manual for this problem.

Here is basic example which will echo "TRUE":

$Var = 8;
if ($Var == 2 || 3) {
echo "TRUE";
}

My question is: why is it echoing TRUE when $Var clearly does not equal 2 OR 3.
If I use "OR" instead of "||" it will still echo TRUE.
If a string is used instead of a number, it will still echo TRUE.
If I use the bitwise "|" operator, it works fine (does not display TRUE).
To me, this seems like a bug since 8 is not at all equal to 2 or3. Any thoughts are much appreciated.

Posted: Sat May 13, 2006 11:52 am
by ambivalent
Since if(2 || 3) evaluates as true, the whole expression becomes true

Try it like this:

Code: Select all

if (($Var == 2) || ($Var == 3)) {

   echo "TRUE"; 


}

works

Posted: Sat May 13, 2006 12:04 pm
by Randy789
Ambivalent,

That does work and I'll do it that way from now on. Still wonder why it would evaluate as true though...

Thank you :)

Re: works

Posted: Sat May 13, 2006 12:12 pm
by ambivalent
Randy789 wrote: Still wonder why it would evaluate as true though...
That's just the way OR works, here's a bit of background: http://en.wikipedia.org/wiki/Truth_table

The manual also has a section on logical operators, which may be helpful: http://ca.php.net/manual/en/language.op ... ogical.php

Re: works

Posted: Sat May 13, 2006 12:53 pm
by aerodromoi
Randy789 wrote:Ambivalent,

That does work and I'll do it that way from now on. Still wonder why it would evaluate as true though...

Thank you :)
Because any string that is not empty and does not consist of a zero or any number greater than zero will always return true...

eg.

Code: Select all

<?php
if (2) echo "yes";
if ("test") echo "yes";
?>
aerodromoi

Posted: Sat May 13, 2006 2:02 pm
by Randy789
That makes sense. Thanks.