4

I want to sort the results to a new array but without the $key so the most UNunique number will be first (or the most duplicated number will be first).

<?php

$a = array (1,1,2,2,2,3,3,3,3,4,4,4,4,4,5);

foreach (array_count_values($a) as $key => $value) {
        echo $key.' - '.$value.'<br>'; 
}

//I am expecting to get the most duplicated number FIRST (without the $key)
//so in that case :
// $newarray = array(4,3,2,1,5); 
?>
2
  • What do you mean by without the $key? Are 4,3,2,1,5 the keys of the new array? Commented Feb 18, 2014 at 8:07
  • iow... The results of the new array would be : $newarray = array(4,3,2,1,5); Thanks ! Commented Feb 18, 2014 at 8:08

3 Answers 3

3
$a = array (1,1,2,2,2,3,3,3,3,4,4,4,4,4,5);

$totals = array_count_values($a);

arsort( $totals );

echo "<pre>";
print_r($totals);

Output

Array
(
    [4] => 5
    [3] => 4
    [2] => 3
    [1] => 2
    [5] => 1
)
Sign up to request clarification or add additional context in comments.

3 Comments

This is WORKING but I was wondering if there is a shorter method :)
Is it better like this? Maybe sorting can be done in same line.. not sure.
@user3301364, My +1 This is the shortest method as it can get !
1

Do like this

<?php
$a = array (1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,6,7,8,9);
$n=array_count_values($a);
arsort($n);
print_r(array_keys($n));

Demo

OUTPUT:

   Array
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
    [4] => 9
    [5] => 8
    [6] => 5
    [7] => 6
    [8] => 7
)

2 Comments

// replace to that line // $a = array (1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,6,7,8,9); // I'm not getting the values of 7,8,9
@user3301364 You can try your input in the Demo link that Nambi has provided.
0
$newarray = array_keys(array_count_values($a));

2 Comments

$a = array (1,1,2,2,2,3,3,3,3,4,4,4,4,4,5); foreach (array_keys(array_count_values($a)) as $key => $value) { echo $value.'<br>'; } // this is not what I'm expecting to get 0 1 2 3 4
You wanted new array not printing it out ;-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.