一个三元运算符中有多个php-if语句


multiple php if statements in one ternary operator

我有多个if语句用于检查四个复选框的值。但是我发现我的代码不好,并且在每个if语句中都包含重复的代码。

我知道一个if语句条件使用三元运算符。但我想在我的代码下面放一个三元运算符。我该怎么做?

信息:三元运算符标准使用condition ? action_if_true: action_if_false;

if (!empty($item->divideto_2)) {
    $col = 6;
    $divide_to = 12 / $col;
}
if (!empty($item->divideto_3)) {
    $col = 4;
    $divide_to = 12 / $col;
}
if (!empty($item->divideto_4)) {
    $col = 3;
    $divide_to = 12 / $col;
}
if (!empty($item->divideto_6)) {
    $col = 2;
    $divide_to = 12 / $col;
}

你可以这样做:

$col = 0;
$divide_to = 12 / (( ! empty($item->divideto_2)) 
                    ? ($col = 6)
                    : ( ! empty($item->divideto_3))
                        ? ($col = 4)
                        : ( ! empty($item->divideto_4))
                            ? ($col = 3)
                            : ( ! empty($item->divideto_6))
                                ? ($col = 2)
                                : $col);

但是,为了更好地可视化,请使用另一种形式。