Logical operators in php

128 Views Asked by At

I dont't understand this. If $_GET['action'] is set and action is not "login" or not "messages" I want to doAction().

My non working code:

if ( isset($_GET['action']) &&  ($_GET['action'] !== "login" || $_GET['action'] !== "messages") )     {
   doAction();
}

If I remove the || it works.

if ( isset($_GET['action']) &&  ($_GET['action'] !== "login") ) {
   doAction();
}

Any hints?

4

There are 4 best solutions below

0
u_mulder On BEST ANSWER

Okay, let's check execution of your if statement:

  1. suppose, action is some_action then isset($_GET['action']) true and $_GET['action'] !== "login" is true

As php has lazy execution (true and true is true) the comparison stopped and your doAction executes, fine, just what we need.

  1. suppose, action is login then isset($_GET['action']) true and $_GET['action'] !== "login" is false and $_GET['action'] !== "messages" is true (as login is definitely not messages). So (true and (false or true)) is true!

  2. finally suppose, action is messages then isset($_GET['action']) true and $_GET['action'] !== "login" is true. Considering lazy execution your doAction runs again.

Okay! Looks like that doAction will work always!

Fix for the problem is using and (&&) instead of or (||) in you if

if (isset($_GET['action']) 
    && ($_GET['action'] !== "login" && $_GET['action'] !== "messages") ) 
    // that should work properly!
1
Mureinik On

You are using the "not equals" operator (!==). If you want to test if the value is login or messages, you should use the == operator:

if ( isset($_GET['action']) && 
     ($_GET['action'] == "login" || $_GET['action'] == "messages") ) {
   doAction();
}
2
dadarya On
if ( isset($_GET['action']) && 
     ($_GET['action'] !== "login" || $_GET['action'] !== "messages") ) {
   doAction();
}
0
Tom On

When testing conditionals in PHP with ||, PHP will test the conditionals in the order they are written and if one of them is true, the whole conditional evaluates to true. This means that for your code if the value of $_GET['action'] is 'messages', the conditional will evaluate to true:

if ( isset($_GET['action']) &&  ($_GET['action'] !== "login" || $_GET['action'] !== "messages") ){
   doAction();
}

Because when the interpreter evaluates $_GET['action'] !== "login" and the value of $_GET['action'] is 'messages', the result of that evaluation is true and thus the code in the if block will be executed. I recommend you change your code to:

if ( isset($_GET['action']) &&  ($_GET['action'] !== "login" && $_GET['action'] !== "messages") ){
   doAction();
}

The || is changed into && and this means that the value of $_GET['action'] cannot be 'login' and it cannot be 'messages'.