2

Is there any function available in PHP to check whether an array is empty or how can I do this without using loop?

For example: $b = array('key1' => '', 'key2' => '', 'key3' => '', 'key4' => '');

How can I check array $b contains empty values without using a loop?

4

7 回答 7

14

Simple:

function allEmpty($array)
{
    return empty(array_filter($array)); // (PHP < 5.3) or
    $array = array_filter($array); return empty($array); // (PHP >= 5.3) or just
    return array_filter($array) === array();
}

function someEmpty($array)
{
    return ($array !== array_filter($array));
}
于 2009-08-26T06:44:19.900 回答
3

Whether you use a loop or some array function, you're still looping through the array so keep it simple and just loop through the array:

function isEmpty($arr) {
  foreach ($arr as $k => $v) {
    if ($v) {
      return false;
    }
  }
  return true;
}

Depending on what you want to define as empty, you may want to only check for empty strings:

function isEmpty($arr) {
  foreach ($arr as $k => $v) {
    if ($v === '') {
      return false;
    }
  }
  return true;
}
于 2009-08-26T06:41:24.133 回答
1

if you want to check for empty strings '' you can use in_array

if(!in_array('', $array)) echo 'array doesn’t contain empty strings';
if(in_array('', $array)) echo 'array does contain at least one empty string';

you might also want to try array_filter with an empty callback method, and compare that to an empty array (or use empty()):

if(empty(array_filter($array))) echo 'array only contains values evaluating to false';
于 2009-08-26T06:42:56.610 回答
1

Simply put, no.

If you don't want to do a literal foreach/for/while, you can use array_walk.

于 2009-08-26T06:43:39.667 回答
1

If that is the specific array you want to check (ie: it only has key=>values and empty is always key=>'') ...

$b = array('key1' => '', 'key2' => '', 'key3' => '', 'key4' => '');
$temp = array_flip($b);
if(count($temp) === 1 && empty($temp[0])){
    echo 'empty';
}

Otherwise you are going to have to use a loop... sorry.

于 2009-08-26T06:59:48.090 回答
0

I usually check it by using following condition:

if(is_array($array) and count($array)) {
 //  ... code here ...
}

That's all.

于 2009-08-26T07:43:25.663 回答
0

A simple

if(!array_filter($array)){
  //Is empty
}
else
{
  //Is not empty
}

do the work.

于 2012-09-05T00:25:42.707 回答