Search code examples
phpif-statementlogical-or

Error in logical or in if condition in PHP


i have file category.php which passes GET['cat'] parameter to process_edit.php

process_edit.php has this code inside..

if (!isset($_GET["cat"]) || !isset($_GET["new_field"])) {
    header ("location: category.php"); 
    exit;
    }   
else {      
    if (! ctype_digit($_GET["cat"])) { 
        header("location: category.php");
        exit; 
    }   
}

but, when i pass 'cat', it is going in first IF statement rather than going in ELSE part.

Can any one suggest what's the error ?


Solution

  • Let's break it down :

    if (!isset($_GET["cat"]) || !isset($_GET["new_field"])) {
    

    This means, if cat is not set, OR new_field is not set, then the condition is true.

    If you pass cat, but you don't pass new_field, the condition will still be true. If you want it to be false, you need to send BOTH cat AND new_field.

    The && requires that all conditions must be true to return true, else it returns false.

    The || requires that any of the given conditions must be true to return true, else it returns false.

    You can find a complete reference of PHP logical operators here :

    http://php.net/manual/en/language.operators.logical.php