Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort an array by number of occurrence of its values?

I have the following array:

$name_arr = array('raj','raj','ganesh','rahul','ganesh','mayur','raj','rahul');

I want to sort it like this:

$final_arr = array('raj','raj','raj','ganesh','ganesh','rahul','rahul','mayur');

How can I achieve it?

like image 254
Ganesh Mulay Avatar asked Dec 19 '22 04:12

Ganesh Mulay


2 Answers

Simple way using array_count_values and arsort:-

$array = array_count_values($name_arr); //get all occurrences of each values
arsort($array);
print_r($array);//print occurrences array
$final_array = array();

foreach($array as $key=>$val){ // iterate over occurrences array
  for($i=0;$i<$val;$i++){ //apply loop based on occurrences number
    $final_array[] = $key; // assign same name to the final array
  }
}

print_r($final_array); // print final array

Output:- https://eval.in/847428

like image 91
Anant Kumar Singh Avatar answered Dec 20 '22 17:12

Anant Kumar Singh


The easiest way to solve this is by using the built-in functions array_count_values() and usort():

<?php

$name_arr = array('raj','raj','ganesh','rahul','ganesh','mayur','raj','rahul');

$valueCount = array_count_values($name_arr);

$final_arr = $name_arr;

usort($final_arr, function ($a, $b) use ($valueCount) {
    return $valueCount[$b] - $valueCount[$a];
});

var_dump($final_arr);

For reference, see:

  • http://php.net/manual/en/function.usort.php
  • http://php.net/manual/en/function.array-count-values.php

For an example, see:

  • https://3v4l.org/4LXVc
like image 37
localheinz Avatar answered Dec 20 '22 17:12

localheinz