0

I need to count the occurrences of each element in a given array. So far, I have managed to achieve this with the exception that it loops all elements and I need to output only those which are unique.

<?php

$array = array('b','b','a','a','b');

foreach ($array as $element) {

    $hold = implode(" ", $array);
    print $element. ' -> ' . substr_count($hold, $element) . '<br />';

}

Thus the output now is:

b -> 3
b -> 3
a -> 2
a -> 2
b -> 3

I want to remove the duplicate elements but if I do array_unique() before I implode() and subsequently make the count, I will get only one occurrence due to the fact that I have removed the repeating elements.

1 Answer 1

2

Use array_count_values() to do it for you.

$counts = array_count_values($array);

foreach ($counts as $match => $count) {
     echo "$match -> $count";
}
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, that would do. Quick question - how do I sort output ascending.
@user3788751: using sort()
How could I wrap $match with sort() when it's not an array?
@user3788751: you haven't told anything about $match but about output. What exactly do you want? Have you checked ksort?
@user3788751: Have you checked ksort? (not sure why you have ignored this advice)
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.