Is there a way in php to count how often a value exists in a large array?

So if I have an array like this:

$array = "1,2,3,4,joe,1,2,3,joe,joe,4,5,1,6,7,8,9,joe";

is there a way to output a new array that tells me (and sorts) which is used most and how many for each?

$result = array(
    [joe] => 4
    [1] => 3
    [2] =>2
    etc...
    )

I've seen the php array_count_values, but can this be sorted by most -> least? or is there an easier way?

Thanks everyone!

share|improve this question
step 1, make it an array using the explode-function in PHP. – Simon André Forsberg Apr 5 '12 at 19:40

1 Answer

up vote 3 down vote accepted

Sort them after counting them with arsort()

$result = array_count_values(explode(',', $array));
arsort($result);

Array
(
    [joe] => 4
    [1] => 3
    [2] => 2
    [4] => 2
    [3] => 2
    [9] => 1
    [8] => 1
    [5] => 1
    [6] => 1
    [7] => 1
)
share|improve this answer
and to make it sort in descending order, use the rsort function instead of ordinary sort. – Simon André Forsberg Apr 5 '12 at 19:40
@NullUserException Yes, I mixup arsort with krsort all the time. – Michael Berkowski Apr 5 '12 at 19:42
Thanks for your help! my code would have been much longer. I appreciate it! – iight Apr 5 '12 at 19:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.