Yenky Yenky - 7 months ago 9
PHP Question

Detect which condition is false in multiple if statement

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
}


I thought about a for loop, but that would need massive code changes.
Maybe someone can point me to the right direction.

Thanks in advance :)

Jens

Answer

Using compact, array_filter and 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';
}

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 ) );