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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Randy789
Forum Newbie
Posts: 3
Joined: Sat May 13, 2006 11:22 am

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

Post 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.
User avatar
ambivalent
Forum Contributor
Posts: 173
Joined: Thu Apr 14, 2005 8:58 pm
Location: Toronto, ON

Post 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"; 


}
Randy789
Forum Newbie
Posts: 3
Joined: Sat May 13, 2006 11:22 am

works

Post 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 :)
User avatar
ambivalent
Forum Contributor
Posts: 173
Joined: Thu Apr 14, 2005 8:58 pm
Location: Toronto, ON

Re: works

Post 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
User avatar
aerodromoi
Forum Contributor
Posts: 230
Joined: Sun May 07, 2006 5:21 am

Re: works

Post 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
Randy789
Forum Newbie
Posts: 3
Joined: Sat May 13, 2006 11:22 am

Post by Randy789 »

That makes sense. Thanks.
Post Reply