Is there a way to put forward the if judgment?

if (
      $row["sale_type"] == "pre" && $row["stock_type"] == "" or
      $row["sale_type"] == "" && $row["delivery_from"] != 0 or
      $row["sale_type"] == "" && $row["delivery_from"] == 0 && $row["stock"] == 0 && $row["stock_type"] == "pre" ) {

      // do something
    }

$row will change, and do something will also change
but the values brought in will all be the same, and the judgment of if or will also look the same.
is there any way to bring it up?
found that there are more than a dozen of the same judgments on the website. If you want to raise them, it is convenient to manage

.
May.26,2022

like this?

function checkXxx($row)
{
    return ($row['sale_type'] == 'pre' && $row['stock_type'] == '' or
      $row['sale_type'] == '' && $row['delivery_from'] != 0 or
      $row['sale_type'] == '' && $row['delivery_from'] == 0 && $row['stock'] == 0 && $row['stock_type'] == 'pre' )
}

if(checkXxx($row) === true)
{
    // do something
}

this kind of requirements are generally implemented by using configuration arrays and do not modify the code as much as possible. Here is an example. The specific implementation can be modified according to the requirements

.
<?php
// 
$rules = [
    [
        'sale_type' => array('===', 'pre'),
        'stock_type' => array('===', '')
    ],
    [
        'sale_type' => array('===', ''),
        'stock_type' => array('!==', 0)
    ]
];
function checkRule($rules, $row) {
    foreach ($rules as $rule) {
        $ruleResult = True;
        foreach ($rule as $ruleKey => $ruleJudge) {
            eval('$ret = $row[$ruleKey] ' . $ruleJudge[0] . ' $ruleJudge[1];');
            if (!$ret) {
                $ruleResult = False;
            }
        }
        //  or 
        if ($ruleResult === True) {
            return True;
        }
    }

    // 
    return False;
}

if(checkRule($rules, $row)){
    // do something
}

just use variables. Don't be too fancy, it looks like effort, a condition, a variable, take a meaningful variable name, if becomes shorter

$isSale1 = xxx;
$isSale2 = xxx;
if ($isSale1 || $isSale2) {
}

Don't think too much. When there are a lot of something , it is still recommended to add if array and logic and & & not to be so fancy. If it is difficult to read, please comment with if .

Menu