PHP 中带有 && 和多个 OR 条件的 If 语句

If statement with && and multiple OR conditions in PHP

我在尝试使下面的语句按我希望的方式工作时遇到问题。

如果至少有一个文本字段未填写,我正在尝试为订单显示错误消息。下面是我的 PHP 代码片段。 'cookieGiftBox' 是用户可以 select 的复选框的名称,如果它被 selected,他们必须在提供的文本字段中根据他们想要的口味输入一定数量的 cookie。当复选框 select 已编辑但未填写任何文本字段时,如何显示错误消息?

<?php
    if (isset($_POST['cookieGiftBox'])
        && (!isset($_POST['sugar']) 
            || ($_POST['chocolateChip'])
            || ($_POST['chocolateChipPecan']) 
            || ($_POST['whiteChocolateRaspberry'])
            || ($_POST['peanutChocolateChip']) 
            || ($_POST['peanutButter'])
            || ($_POST['tripleChocolateChip']) 
            || ($_POST['whiteChocolateChip'])
            || ($_POST['oatmealRaisin']) 
            || ($_POST['cinnamonSpice'])
            || ($_POST['candyChocolateChip']) 
            || ($_POST['butterscotchToffee'])
            || ($_POST['snickerdoodle']))) {
        $error.="<br />Please enter an Amount for Cookie Flavors";
    }
?>

&& 优先于 ||,因此您必须使用括号才能获得预期结果:

if (isset($_POST['cookieGiftBox']) && (!isset($POST['sugar']) || ...)

实际上,要检查是否选择了 nothing,您可以这样做: if checkbox is checked and not (sugar is checked or chocolatechip is checked) 或等效项: if checkbox is checked and sugar is not entered and chocolatechip is not entered...。 如果您想了解更多信息,请搜索有关 Boolean algebra.

的信息

更新:在你的例子中,在正确的语法中,我作为例子的句子是这样的(对于第一句话,注意不是(!)和字段周围的括号,而不是复选框):

if (isset($_POST['cookieGiftBox']) &&
    !(
       isset($_POST['sugar']) ||
       isset($_POST['chocolatechip'])
     )
) { error ...}

或者第二句,可能更容易理解(注意&&而不是||):

if (isset($_POST['cookieGiftBox']) &&
    !isset($_POST['sugar']) &&
    !isset($_POST['chocolatechip'])
) { error...}

如果在选中礼品盒复选框时设置了糖、巧克力片等字段的 none,则使用 ands 确保它仅为真(并因此显示错误)。 因此,如果复选框被选中,并且没有设置任何字段,它看起来像这样: (true && !false && !false) 等同于 (true && true && true)true,所以显示错误。 如果选中该复选框并输入糖,它将如下所示: (true && !true && !false), equ.到 (true && false && true),等于。到 false,因此不会显示错误。 如果同时输入糖和巧克力片也不会显示错误。

我有类似的问题:

我尝试使用:

if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') || ($this->context->controller->php_self != 'product') || ($this->context->controller->php_self != 'index')){ ... }

不行,我改成:

if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') && ($this->context->controller->php_self != 'product') && ($this->context->controller->php_self != 'index')){ ... }

不知道对不对?

编辑。这是不正确的,但现在我不知道如何解决它。