PHP if not statements

后端 未结 7 2064
南方客
南方客 2020-12-17 10:46

This may be the way my server is set up, but I\'m banging my head against the wall. I\'m trying to say that if $action has no value or has a value that is not \

7条回答
  •  醉梦人生
    2020-12-17 11:09

    Your logic is slightly off. The second || should be &&:

    if ((!isset($action)) || ($action != "add" && $action != "delete"))
    

    You can see why your original line fails by trying out a sample value. Let's say $action is "delete". Here's how the condition reduces down step by step:

    // $action == "delete"
    if ((!isset($action)) || ($action != "add" || $action != "delete"))
    if ((!true) || ($action != "add" || $action != "delete"))
    if (false || ($action != "add" || $action != "delete"))
    if ($action != "add" || $action != "delete")
    if (true || $action != "delete")
    if (true || false)
    if (true)
    

    Oops! The condition just succeeded and printed "error", but it was supposed to fail. In fact, if you think about it, no matter what the value of $action is, one of the two != tests will return true. Switch the || to && and then the second to last line becomes if (true && false), which properly reduces to if (false).

    There is a way to use || and have the test work, by the way. You have to negate everything else using De Morgan's law, i.e.:

    if ((!isset($action)) || !($action == "add" || $action == "delete"))
    

    You can read that in English as "if action is not (either add or remove), then".

提交回复
热议问题