phparraysassociative-arrayis-empty

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!';
}

Solution

  • 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
    }