Psyche
Psyche

Reputation: 8773

Weird if condition issue in PHP

I have the following code:

$_SESSION['user_role'] = 1;

if ($_SESSION['user_role'] != '1' || $_SESSION['user_role'] != '2') {
    return false;
} else {
    return true;
}

Why does this if() always returns false?

Upvotes: 0

Views: 81

Answers (2)

knittl
knittl

Reputation: 265191

Because user_role cannot be 1 and 2 at the same time. Let's go through all possible values:

1: != 2
2: != 1
anything else: != 1, != 2

You probably wanted to write your condition as follows

if(!($_SESSION['user_role'] == 1 || $_SESSION['user_role'] == 2)) {
  return false;
} else {
  return true;
}

which is equivalent to:

if($_SESSION['user_role'] != 1 && $_SESSION['user_role'] != 2)) {
  return false;
} else {
  return true;
}

(boolean algebra)

Your condition can even be written without an if:

return $_SESSION['user_role'] == 1 || $_SESSION['user_role'] == 2;

PS. don't use magic values


For the sake of completeness, here's a truth table:

A := user_role == 1
B := user_role == 2

  | A | B | !B | !A | A or B | !A or !B | !(A or B) | !A and !B
--+---+---+----+----+--------+----------+-----------+-----------
1 | T | F |  T |  F |      T |        T |        F  |         F
2 | F | T |  F |  T |      T |        T |        F  |         F
--+---+---+----+----+--------+----------+-----------+-----------
3 | F | F |  T |  T |      F |        T |        T  |         T
4 | F | F |  T |  T |      F |        T |        T  |         T
5 | F | F |  T |  T |      F |        T |        T  |         T
...

From the table you can immediately see that !(A or B) is equivalent to !A and !B

Upvotes: 9

Your Common Sense
Your Common Sense

Reputation: 157839

A code for you to get it right:

$condition1 = ($_SESSION['user_role'] != '1');
$condition2 = ($_SESSION['user_role'] != '2');
$result     = ($condition1 || $condition2);
var_dump($condition1,$condition1,$result);

I am always doing this if in doubts of the result of some logical expression.

Upvotes: 0

Related Questions