检测多个 if 语句中的哪个条件为假


Detect which condition is false in multiple if statement

我试图缩短我的代码,所以我来缩短以下类型的if语句:

// a,b,c,d needed to run
if ( empty(a) ) {
    echo 'a is empty';
} elseif ( empty(b) ) {
    echo 'b is empty';
} elseif ( empty(c) ) {
    echo 'c is empty';
} elseif ( empty(d) ) {
    echo 'd is empty';
} else {
  // run code with a,b,c,d
}

有没有办法检测哪一个条件是假的(是emtpy)?

if ( empty(a) || empty(b) || empty (c) || empty(d) ) {
     echo *statement n*.' is empty';
} else {
  // run code with a,b,c,d
}

我想过一个 for 循环,但这需要大量的代码更改。也许有人可以指出我正确的方向。

提前致谢:)

延斯

您可以为每个条件设置一个变量并输出此变量

if ( (($t = 'a') && empty($a)) || (($t = 'b') && empty($b)) || (($t = 'c') && empty($c)) || (($t = 'd') && empty($d)) ) {
     echo "{$t} is empty";
} else {
  // run code with a,b,c,d
}

赋值 ( $t='a|b|c|d' ) 将始终为真,如果 testet var 为空,您的条件将因条件true && false而失败

但就可读性而言,我宁愿选择其他任何答案。

使用 compactarray_filterarray_diff

$arr = compact( 'a', 'b', 'c', 'd' );
if( count( $empty = array_diff( $arr, array_filter( $arr ) ) ) )
{
    echo key( $empty ) . ' is empty';
}
else
{
    echo 'OK';
}

这样,在$empty中,您拥有所有空值。因此,您可以对所有键发出警告:

echo 'Empty: ' . implode( ', ', array_keys( $empty ) );

对于这种情况,我建议您使用 switch,这是更优化的方式,如下所示:

$empty = "";
switch ($empty) {
    case $a:
        echo "a is empty"
        break;
    case $b:
        echo "b is empty"
        break;
    case $c:
        echo "c is empty"
        break;
    default:
        echo "nothing is empty";
}

就个人而言,我可能会使用变量。但这只是我喜欢他们,有些人不喜欢

// the variables somewhere else in your code
$a = 1;
$b = null;
$c = '';
$d = 4;

// do your check
$arr = ['a','b','c','d']; // the names of the variables you want to check
foreach($arr as $var) {
    if(empty($$var)) {
        echo $var . ' is empty'.PHP_EOL;
    }
}

将输出

b 为空
C 为空

使用 array_search()

<?php 
$arr = array('a'=>1,'b'=>2,'c'=>null,'d'=>4); //make an array of variables
echo "Null variable : ".array_search(null, $arr); // check for null item
?>

这将输出:

Null variable : c