Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list elements of an array in the order of number of their occurrences?

I have an array like this.

$array = array(
'Element1', 
'Element2', 
'Element3', 
'Element1', 
'Element1', 
'Element4', 
'Element4', 
'Element2', 
'Element2', 
'Element2', 
'Element2', 
'Element4', 
'Element5', 
'Element5' );

I want an array like this as output.

$output = array('Element2' , 'Element1', 'Element4', 'Element5', 'Element3');

So, what i want is:

  1. Remove all the elements from the array which repeat.
  2. Order the output array in such manner that the element which occured most in the input array is on top.
like image 728
Ayush Mishra Avatar asked Dec 04 '25 07:12

Ayush Mishra


1 Answers

Use array_count_values() and sort()

like image 122
Jessica Avatar answered Dec 07 '25 00:12

Jessica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!