Reputation: 83695
Is there a simpler way than this?
$isArrayEmpty = true;
foreach ($array as $value) {
if (!empty($value)) {
$isArrayEmpty = false;
}
}
Seems kinda redundant.
Upvotes: 1
Views: 148
Reputation: 42140
$isArrayEmpty = empty( array_filter( $array ) );
Edit
As noted in the comments the above expression will not work - it will throw a fatal error. This is because empty
can only operate on variables and not the return value of a function (or language construct)
So as etarion suggested the correct answer in the same spirit of my answer is:
$isArrayEmpty = !array_filter( $array );
Upvotes: 6
Reputation: 157892
no, it's not redundant. it's perfectly legitimate way. nothing bad in this code. just add break
to it.
I'd even say your current approach is the best one, just keep it.
For frequent use you can wrap it in a function
Upvotes: 1
Reputation: 176675
Here's one way of doing it using array_reduce
:
$isArrayEmpty = array_reduce($array, function($acc, $e) { return $acc && empty($e); }, true);
Upvotes: 1