How to count same value comma separated string in php

If you want to get duplicate values count in an comma separated string in php, first need to create array using explode function.

Many time user ask me how to count duplicate value comma separated string in Laravel 5.

The array_count_values() function counts all the values of an array.

$colorstring = 'A,A,B,C,D,A,B';
$colordata = explode(',', $colorstring);
$vals = array_count_values($colordata);

Output

Array ( [A] => 3 [B] => 2 [C] => 1 [D] => 1 ) 

Leave a Reply

Your email address will not be published. Required fields are marked *