1

How to calculate the numbers of arrays whose values are empty. For example, I have array result:

    Array (
       [0] => 'A',
       [1] => 'B',
       [2] => 'C',
       [3] => '',
       [4] => '',
       [5] => 'F',
       [6] => '')

Here are 3 empty array values (index 3,4,6), so how the way get the number of empty array values

4 Answers 4

5
$c = 0;
foreach($a as $v) {
    if ($v === '') { 
        $c++;
    }
}
echo "count: $c\n";

-- OR --

$t = array_count_values($a);
echo "count: {$t['']}\n";

PHP manual: http://php.net/manual/en/function.array-count-values.php

Sign up to request clarification or add additional context in comments.

Comments

3

For multi-dimensional arrays (and flat arrays too) you can use

 $a =  Array (
   0 => 'A',
   1 => 'B',
   2 => 'C',
   3 => '',
   4 => '',
   5 => 'F',
   6 => '',
   7 => ['','']
  );

$total = 0;

array_walk_recursive($a, function($i) use (&$total){
 if($i === '') ++$total;
});

echo $total;

Output

5

Sandbox

Probably the shortest way is this:

echo count(array_intersect($a, ['']));

But it doesn't work with nested arrays

Sandbox

Comments

1
$a = ['1', '2', '', '', '5', ''];
echo count($a) - count(array_filter($a)); // output: 3

4 Comments

you can improve your answer by adding intention of your code
@AbdulWaheed Thank you, but I think this code is too simple and clear at a glance
@ArtisticPhoenix Yes, if only statistics ''
array_filter() is greedy and in a few scenarios it will return inaccurate results due to falsey, zeroish, null values.
-1

Try this:

<?php
$count = 0;
for ($i =0; $i < length($array); $i++) {
  if ($array[$i] == '')
    $count++;
}
?>

1 Comment

"Try this" does not make for a good answer. You should explain how and why this solves their problem. I recommend reading, "How do I write a good answer?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.