在多个if语句中检测哪个条件为假 [英] Detect which condition is false in multiple if statement
本文介绍了在多个if语句中检测哪个条件为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试缩短代码,因此也缩短了以下类型的if语句:
I try to shorten my code, and so I come along to shorten the following type of if statement:
// 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
}
有没有一种方法可以检测出哪个条件为假(为空)?
Is there a way to detect which one of the conditions was false (is emtpy)?
if ( empty(a) || empty(b) || empty (c) || empty(d) ) {
echo *statement n*.' is empty';
} else {
// run code with a,b,c,d
}
我想到了一个for循环,但是那需要大量的代码更改. 也许有人可以指出我正确的方向.
I thought about a for loop, but that would need massive code changes. Maybe someone can point me to the right direction.
先谢谢您了:)
詹斯
推荐答案
使用compact
,array_filter
和array_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
中,您将拥有所有空值.因此,您可以对所有按键发出警告:
By this way, in $empty
you have all empty values. So you can echo a warning for all keys:
echo 'Empty: ' . implode( ', ', array_keys( $empty ) );
这篇关于在多个if语句中检测哪个条件为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文