DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Array Group By Count

03.26.2007
| 17900 views |
  • submit to reddit
        Function for group by count of elements, with a optional parameter for sort on asc and desc mode

<?php
function ArrayGroupByCount($_array, $sort = false) {
   $count_array = array();

   foreach (array_unique($_array) as $value) {
       $count = 0;

		foreach ($_array as $element) {
		    if ($element == $value)
		        $count++;
		}
	
		$count_array[$value] = $count;
	}
	
	if ( $sort == 'desc' )
		arsort($count_array);
	elseif ( $sort == 'asc' )
		asort($count_array);

	return $count_array;
}
?>