View Full Version : Need help understanding && and ||

01-04-2008, 04:57 PM
This script is working but I do not understand it. I am thinking that the || comparison should be used, but the only way it will give the right result is with &&.

This is what I am seeing: If neither $_SESSION['id'] or $_SESSION['edit'] are set I want the statement to return TRUE. Therefore I think I should have to use ||. I am thinking that by using the && comparison that both would have to not be set for the statement to return true.


$_SESSION['id'] = '12345';
// $_SESSION['edit'] = 'update';

if (!isset($_SESSION['id']) && !isset($_SESSION['edit']))
echo "<br/>Neither session is set.";
else echo "Good to go!";

Please explain.


01-04-2008, 05:13 PM
You contridict your self:

neither $_SESSION['id'] or $_SESSION['edit']

Neither implies that you want to check that both $_SESSION['id'] AND $_SESSION['edit'] are not set.

If you use OR (||) the if statement will return true if only one of the session variables is not set.

If you use AND(&&) both other the session variables will have to be not set in order to return true.

01-04-2008, 06:38 PM
Ok I took another look at it and played with it for half an hour. It is working the way it should. What I want to do is have it return TRUE if neither are set. So by checking both with AND if one is set then it will return false.

I appreciate you reading and responding.

Problem Solved!

01-04-2008, 06:57 PM
There's actually a name for this, it's called De Morgan's Law (http://en.wikipedia.org/wiki/De_Morgan's_laws). It states that the condition !(A or B) is equal to the condition (!A and !B). So if you want to test to see if A is false or B is false, you have to use &&.

To get it straightened out in my brain, when I had a brain that is, I replaced each expression in the condition with a "T" or an "F", then looked at the "if" statement again, using the "T"'s and "F"s.

$_SESSION['id'] = "something";

if (!isset($_SESSION['id']) || !isset($_SESSION['edit']))
//replacing expressions with T or F:
//if (F || T) //this evaluates to T

if (!isset($_SESSION['id']) && !isset($_SESSION['edit']))
//replacing expressions with T or F:
//if (F && T) //this evaluates to F

Edit: Whoops, looks like you have it figured out. I got distracted in the middle of my reply :p