PHP 仅在条件匹配时才包含条件


PHP include condition in if only when criteria matched

我想构建一个包含/排除最终标准的if then语句。

例:

$vanilla_on=true;
$sugar_on=false;
$flour_on=true;
$vanilla=10;
$sugar=2;
$flour=100;
// As I set $vanilla_on to false, it doesn't appear in my if statement, if it was set to true, it would be added && ($vanilla < 100)
if ( ($sugar>2) && ($flour>90) )
{
  // ok
}

基本上,如果相应的布尔值设置为 true,我只想检查香草、糖和面粉条件。因此,如果我有 vanilla_on=false,那么包含多少单位的香草并不重要,因为我们只会检查糖和面粉的条件。

// these are "switches" that will tell the if statement which components to check
$vanilla_on=true;
$sugar_on=false;
$flour_on=true;
// components
$vanilla=10;
$sugar=2;
$flour=100;
// only check that the component meets the thresholds *if* it's "on"
if ( ($sugar>2 || !$sugar_on) && ($flour>90 || !$flour_on) && ($vanilla < 100 || !$vanilla_on) )
{
  // ok
  echo "OKAY!";
}

其工作方式是这样的:你有一个 if 语句,该语句的计算结果必须为 TRUE 才能"正常"。假设您需要检查所有三个组件以确保它们都在阈值内,则所有 3 个条件都必须为 true,才能使整个语句的计算结果为 true。 如果 AND 中只有一个条件是假的,那么整个事情都是假的。

但是,假设您不关心使用了多少香草。只要在阈值内测量糖和面粉,您使用多少香草就与确定事情是否正常无关。为此,您将每个单独的组件包装在括号中,并使用其相应的"on"布尔值或它。

简而言之,如果 $vanilla_on 为 false,这意味着您不在乎使用多少香草,则取布尔值 true 和 OR 的相反值进行阈值比较。由于 (true OR false) 的计算结果始终为 true,因此无论您使用多少香草,if 语句的这一部分始终返回 true。 同样,如果 $sugar_on 为真,则相反的值为假,因此为了使 if 语句的这一部分为真,我们现在仅依靠糖阈值落在通过小于比较确定的范围内。

简而言之,将问题分解为单个组件,然后将它们全部分解在一起。

$vanilla_ok = true;
if ($vanilla_on === true && $vanilla < 5) {
    $vanilla_ok = false;
}
if (... && $vanilla_ok)
{
    // ok
}
好的,

我找到了一个简单的方法。

if (a)
{
if (b) {c=true} else {c=false}
}
else
{
c=true
}
repeat for all _on variables
if (c) && (d) ...