View Full Version : Why won't this work?

02-24-2010, 09:33 PM
I'm trying to check three conditions using one if statement. I've included the "!" to check if something doesn't match what I want.

Here's what I have:

if (!isset($_SESSION['login']) && !strlen($key) == 128 && !$key == $_SESSION['login']){
//do something

Do I have to use "||" instead of "&&", or can I somehow still use "&&"?

Thanks for the help!

02-24-2010, 09:35 PM
You want to use "!=" to check for not equal.

if (!isset($_SESSION['login']) && strlen($key) != 128 && $key != $_SESSION['login']){

02-24-2010, 09:53 PM
You want to use "!=" to check for not equal.

if (!isset($_SESSION['login']) && strlen($key) != 128 && $key != $_SESSION['login']){

Thanks, I see! So I was doing it totally backwards.

For some reason though, it still doesn't execute my IF statement if just one of the conditions doesn't match.

If none of the conditions match, then it executes, but if just one matches then it never executes.

02-24-2010, 10:11 PM
This isn't right.

if (!isset($_SESSION['login']) && strlen($key) != 128 && $key != $_SESSION['login']){

If $_SESSION['login'] DOESN'T exist AND $key != 128 AND $key != $_SESSION['login'] (which err.... doesn't exist at this point since we ensured that in the first expression.....).

Looks to me like this should be:

if (!isset($_SESSION['login']) || strlen($key) != 128 || $key != $_SESSION['login'])

So in phrase format, if you do not have a session login OR the session login doesn't match the key OR the key is not 128 characters in length, execute this code block. Personally, I can't see you needing the strlen check in there at all, I would presume that $key is coded somewhere and loaded, not provided by the client. Also, look into using strcmp for you're comparisons instead of == and !=. PHP is a string based language so it will support the comparison, but you will find most other common mainstream langauages do not.

02-24-2010, 10:12 PM
Using the &&, you're saying that all three conditions have to be true, (false), for the code within the block to execute. If you want the code to run if only one or more of the conditions are true, (false), use ||.

02-24-2010, 10:17 PM
Thanks everyone! That fixed it! :)