Skip to content
Advertisement

Count number of columns in array php?

I have a simple function to count numbers of columns with specific value in the array:

echo 'Status-accept: ' . array_count_values(array_column($array, 'status'))['Accept'];

it works well while accept exists in the array. If not I get Undefined index: Accept. My array looks like that:

array{
...
["status"]=>
    string(7) "Accept"
...
}

How can I add something like isset here?

Advertisement

Answer

With oneliner is it not possible (or the code will be messy), so you have to store a value with counts somewhere and then use ?? operator for example:

$counts = array_count_values(array_column($array, 'status'));
echo 'Status-accept: ' . ($counts['Accept'] ?? 0);

As a oneliner you can:

echo 'Status-accept: ' . count(array_filter($array, function($v) { return $v['status'] === 'Accept'; }));

Here we filter all items where status field is 'Accept' and then just count filtered items. If there are no items – filtered array will be empty and we’ll get 0 as result.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement