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.
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
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;
}))
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)
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 (===)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.