How to search for a string other than specify in array count values function?

Haziq Asyraff :

I'm trying to create a chart using Chart.js, however, there is a problem when trying to count values from an array. There is a key in array called reference with values of Facebook, Google, Invitation, [Other than all that].

array_count_values(array_filter(array_column(($participants->toArray()), 'reference')))['Facebook'] ?? '0';
array_count_values(array_filter(array_column(($participants->toArray()), 'reference')))['Google'] ?? '0';
array_count_values(array_filter(array_column(($participants->toArray()), 'reference')))['Invitation'] ?? '0';
array_count_values(array_filter(array_column(($participants->toArray()), 'reference')))['Other'] ?? '0';

I want the last line which is looking for other string. Other should be a string that is other than Facebook, Google and Invitation. However, if there is any other cleaner/proper way of doing it would also be helpful. Thanks!

Nick :

I think this would be cleaner and more efficient:

$counts = array_count_values(array_filter(array_column(($participants->toArray()), 'reference')));
$facebook = $counts['Facebook'] ?? 0;
$google = $counts['Google'] ?? 0;
$invitation = $counts['Invitation'] ?? 0;
$others = array_sum($counts) - $facebook - $google - $invitation;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=293265&siteId=1