PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

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

 October 28, 2022     arrays, associative-array, is-empty, php     No comments   

Issue

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
}


Answered By - MonkeyZeus
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing