Re: if statement with or comparison (newbie)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




----- Original Message ----- From: "JD" <jd_borozo@xxxxxxxxxx>
To: <php-general@xxxxxxxxxxxxx>
Sent: Friday, September 08, 2006 11:03 PM
Subject:  if statement with or comparison (newbie)


I'm trying to set up a simple conditional, something like this:

If my_variable is NOT equal to (black or white)
   echo "wrong color"
else
   echo "right color"

Here is what I have tried:

    if ($_REQUEST['id'] != ("black" or "white")) {


What PHP (and any parser, for that matter) will try to do is first solve the innermost parenthesis. ("black" or "white"). Many typed languages would give an error at this point, but PHP tries to convert anything it gets to whatever is more useful at the moment. Since both "black" and "white" are not null or empty strings, they are evaluated as true for the logical comparison and true or true is always true. Now, $_REQUEST['id'] might be whatever it is, but dealing with booleans as we are this far, anything but missing or empty string will be true as well, which will give you the second option.


Now, first of all, avoid negative comparissons, negative booleans are horrible. Try first to straighten them up or you might get thoroughly confussed:


if ($_REQUEST['id] == 'black' or $_REQUEST['id'] == 'white') {
   echo 'right color';
} else {
echo 'wrong color'';
}

And so as you know why it is good to straighten negative booleans, this would be the twisted way

if ($_REQUEST['id] != 'black' and $_REQUEST['id'] != 'white') {
echo 'wrong color'';
} else {
   echo 'right color';
}

Notice that not only the comparisson changed but now they are joined by an AND instead of an OR and the then and else parts are swapped.

Satyam


        echo "wrong color";

    } else (

        echo "right color";

    )

However, no matter what I enter, I always get response "right color".

I should add that if I change the if statement to:

    if ($_REQUEST['id'] != ("black"))

then I get "right color" when I enter "black" and "wrong color" for everything else.

Would you please point out what's the trivial thing I'm missing here...

jd

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux