Search code examples
phpconditional-statementslogical-operatorsisset

Redundant condition in PHP code or not?


Many PHP developers write the following conditional statement:

if (isset($_POST['action']) and $_POST['action'] == 'someValue') {
  something();
}

What is it useful for to write this conditional statement?

When I look at it, it seems that if $_POST['action'] == 'someValue' implies that isset($_POST['action'] == TRUE.

So, it seems that the following conditional statement will do the same:

if ($_POST['action'] == 'someValue') {
      something();
}

Solution

  • If you just call:

    if ($_POST['action'] == 'someValue') {
       something();
    }
    

    and $_POST["action"] is not set, then the default PHP behaviour is to complain about undefined index, which will result in a direct string output. Now consider if your PHP request was all about sending a JSON back to the client... Your JSON would be a malformed one.

    Another issue, consider the following:

    if ($_POST['action'] == 'someValue') {
       something();
    }
    ...
    header("Location: foo.php");
    

    Sorry, no chance since your notice about undefined index preceed the header and this is a no-no. It will not work since the default behaviour of PHP (considering error reporting is ON) is to spit warnings in string format, thus messing the flow of your script.

    Of course, you could silencing these errors with this:

    if (@$_POST['action'] == 'someValue') {
       something();
    }
    

    but this is an equally bad practice, it doesnt make the program better but slower and harder to catch errors.