0

Here is my code:

<?php
$array = array("world", 1, "hello", 1, "hello", "hello", "how");
$new_array = array_count_values($array);
print_r($new_array);
?>

/* Output:
Array
(
    [world] => 1
    [1] => 2
    [hello] => 3
    [how] => 1
)

Now I want to sort the result based on the new array's value. So this is expected output:

/* Expected Output:
Array
(
    [hello] => 3
    [1] => 2
    [world] => 1
    [how] => 1
)

How can I do that?

Note: The order for the same values doesn't matter.

stack
  • 10,280
  • 19
  • 65
  • 117

3 Answers3

8

You can make use of arsort() to sort the array by its value:

<?php
$array = array("world", 1, "hello", 1, "hello", "hello", "how");
$new_array = array_count_values($array);
arsort($new_array, SORT_NUMERIC);
print_r($new_array);
?>

which will output:

Array
(
    [hello] => 3
    [1] => 2
    [world] => 1
    [how] => 1
)
Raptor
  • 53,206
  • 45
  • 230
  • 366
  • thank you .. upvote. Just I don't know why [it sorts as **asc** for me](https://i.stack.imgur.com/GspqI.png). Do you know how can I make it **desc** ? – stack Mar 08 '17 at 06:53
  • Sorry, a typo in code. should be `arsort()`. – Raptor Mar 08 '17 at 07:07
0

Pleas try below code

    <?php

    $array = array("world", 1, "hello", 1, "hello", "hello", "how");

    $new_array = array_count_values($array);
    asort($new_array);
    print_r($new_array);    
Nishant Nair
  • 1,999
  • 1
  • 13
  • 18
0

use arsort($new_array); for sort in desc order and asort($new_array); for asc order

Sudhanshu Jain
  • 494
  • 3
  • 11