Richard Knop
Richard Knop

Reputation: 83695

A simple way to find out if all array values are empty?

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

Answers (5)

Richard Testani
Richard Testani

Reputation: 1482

Can't you just...

if(empty($array)) {  //do this  }

Upvotes: -1

meouw
meouw

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

Your Common Sense
Your Common Sense

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

greg606
greg606

Reputation: 491

$foo = implode('', $array);
$isArrayEmpty = empty($foo);

Upvotes: 0

Paige Ruten
Paige Ruten

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

Related Questions