Anderson Montes De oca Anderson Montes De oca - 4 months ago 14
PHP Question

How to order a php array with duplicate

Good night, do not speak much English. what I need is to sort an array by ordern duplicate
Do not know how I leave here the code to see if someone can help me

$arr = array(1=> 'Love is true',
2=> 'Love is true',
3=> 'Hello Word',
4=> 'Hello Word',
5=> 'Hope',
6=> 'Hope',
7=> 'Love is true',
8=> 'Hello Word',
9=> 'Hello Word',
10=>'Hope',
11=>'Hello Word',
12=>'Hope',
13=>'Hello Word',
14=>'Hello Word',
15=>'Hello Word');
print_r($arr);

Hello Word >duplicate > 8
Hope >duplicate > 4
Love is true >duplicate > 3

I need Order Retun # print_r($arr);

Example of how I want


Hello Word position 1# In array
Hope 2# In array
Love is true 3# In array

example

Array
(
[0] => Hello Word position
[1] => Hope
[2] = Love is true
)

Answer

You can do it like this:

$count = array_count_values($arr); // count each repetition
arsort($count); // sort the values
$array = array_keys($count); // get the expected array
print_r($array);

That will output:

Array
(
    [0] => Hello Word
    [1] => Hope
    [2] => Love is true
)

See it in action here.


You can get some references for the functions used in this answer below:

  • array_count_values: Counts all the values of an array;
  • asort: Sort an array and maintain index association;
  • array_keys: Return all the keys or a subset of the keys of an array.


You can var_dump each step of the process to see what's going on.