1

I have an array that looks like this:

$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);

I want to get the most frequent item followed by the next most frequent item until I get to the least frequent item and then create another array with this information that looks like this:

$frequencies=array("1"=>4,"4"=>3,"5"=>2,"6"=>1,"7"=>1)

How can I achieve this, please help.

DonxScott
  • 29
  • 5

2 Answers2

2

You have to Use array_count_values()

<?php

$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);

$recs1 = array_count_values($recs);

print_r($recs1);

https://eval.in/973006

Or if you want numbers need to be ascending order(which are keys in your final array) then use ksort()

<?php

$recs = array(1,4,7,1,5,4,1,12,1,4,6,5);

$recs1 = array_count_values($recs);
ksort($recs1);
print_r($recs1);

https://eval.in/973163

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0
$recs = array(1,4,7,5,5,4,5,12,1,4,6,5);
//array_count_values — Counts all the values of an array
$recs1 = array_count_values($recs);
//to get the most frequent item followed by the next most 
//frequent item until I get to the least frequent item 
//use `arsort` — Sort an array in reverse order and maintain index association
arsort($recs1);
print_r($recs1);

Demo

Bhaskar Jain
  • 1,651
  • 1
  • 12
  • 20