How to count same value comma separated string in Laravel 8

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

Count duplicate value in array using below function.

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

$getdetail = DB::table('search_logs')
		->where('user_id',$userid)
		->where('parent_id',Auth::user()->id)
		->select('shape', 'color', 'cut')
		->get();

$colorstring = '';
foreach ($getdetail as $value) {
	if(!empty($value->color))
	{
		$colorstring.= $value->color.',';	
	}
}

$colordata = explode(',', trim($colorstring,','));
$vals = array_count_values($colordata);

Output

Array ( [F] => 10 [L] => 9 [O] => 8 [M] => 6 [N] => 7 [G] => 5 [H] => 4 ) 

Leave a Reply

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