简体   繁体   中英

How to see if an array of associative arrays is empty in php

I have a fairly easy issue where I need to see if an associative array of arrays is empty in php. My array looks like this:

array (
  'person1' => 
  array (
  ),
  'person2' => 
  array (
  ),
  'person3' => 
  array (
  ),
)

In my case, the three array's for the three people holds nothing so I need a test whether this is empty. I have done this which works:

    if ( empty($form_values['person1']) && empty($form_values['person2']) && empty($form_values['person3'] ) ){
        echo 'values empty!!';
    }

But I was hoping something a bit more cleaner with using empty like the following:

if (empty( $form_values )) {
  echo 'HI!';
}

If you're looking for a one-liner then you could do something like:

$form_values = array (
  'person1' => 
  array (
  ),
  'person2' => 
  array (
  ),
  'person3' => 
  array (
  ),
);

if(array_sum(array_map(function($v){return !empty($v);}, $form_values)) === 0)
{
    // empty
}
else
{
    // not empty
}

Use a loop that tests each nested array. If none of them are non-empty, the whole array is empty.

$is_empty = true;
foreach ($form_values as $val) {
    if (!empty($val)) {
        $is_empty = false;
        break;
    }
}

You can use array_filter() to filter all of the empty array elements. You can then use empty to check if the result is empty then.

I've shorthanded the arrays so it's a easier to read since the arrays are empty. array() will work the same.

$form_values = [
  'person1' => [],
  'person2' => [],
  'person3' => []
];

if (empty(array_filter($form_values))) {
    // empty
} else {
    // not empty
}
<?php

$data = 
[
    'pig' => [],
    'hog' => [],
    'sow' => []
];

$all_empty = array_filter($data) === [];
var_dump($all_empty);

Output:

bool(true)

From the manual for array_filter:

If no callback is supplied, all empty entries of array will be removed. See empty() for how PHP defines empty in this case.

Note that if an item was deemed as empty, like an empty string, it would still return true. This test may not be strict enough.

More explicitly:

if (array_filter($data, function($v) {return $v !== []; }) === []) {}

Filter out all items that aren't the empty array. What we'll be left with is an empty array if all items are an empty array.

Or search and compare:

if (array_keys($data, []) == array_keys($data)) {}

Check keys belonging to items containing the empty array match the keys of the array. Or rather all items (if they exist) are the empty array.

Note that an empty array will also satisfy the three solutions above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM