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
You can go with setting a variable for each condition and output this
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
}
The assignment ($t='a|b|c|d' ) will always be true and it the testet var is empty your condition will fail because of true && false in the condition
But in terms of readibility i would rather go with any of the other answers.
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With