0

I have an array like this:

$items = ['a', 'b', null, null]; 

I want count [nulls] in this array which is 2.

But: Without replacing them before working with. Like this:

$items = array_replace($items,array_fill_keys(array_keys($items, null),''));

array_count_values($items);

And: Without removing them from the array and put them out of the total. Like this:

count($items) - count(array_filter($items));

I'm trying to know more better solutions.

2
  • 2
    What's wrong with the second approach? Don't want to count() twice? Commented Dec 29, 2019 at 10:40
  • Repeated null values or all null values? [null, 1, null, null] is that two or three? Commented Dec 29, 2019 at 20:04

4 Answers 4

4

You could array_filter on the null values and count once on the result:

count(array_filter($items, function ($item) { return $item === null; }))

or in PHP 7.4:

count(array_filter($items, fn($item) => $item === null));

Demo: https://3v4l.org/TOHdP

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

Comments

1

Usually the best is to be explicit, so simply iterate over the input array and count:

<?php
$items = ['a', 'b', null, null]; 
array_walk($items, function($value) use (&$count) {
    if ($value === null)
      $count++;
});
var_dump($count);

The output obviously is:

int(2)

Comments

0

You can use array_count_values method. you can use it like this:

- Solution 1

$items = ['a', 'b', null, null]; 

$counts = 0;
foreach(array_count_values($items) as $item => $counter){
    $counts += $counter;
}
echo count($items) - $counts;

PS: array_count_values() just count string and integers.

- Solution 2

Or you can use array_filter to create null values array and count it.

echo count(array_filter($items, function ($item) { 
    return $item === null; 
}))

Comments

0

No need for array_filter

$items = ['a', 'b', null, null]; 

echo(count(array_keys($items, null, true))); // Output: 2

Note the third argument must be true if you only want null to be counted, as true means do strict comparison (===)

Comments

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.