Search code examples
phparraysechoarray-filter

What is the best/fastest way to echo duplicate array values and their count in php


I need your advice if there is a better (and faster) way to output duplicate array values and their count in php.

Currently, I am doing it with the below code:

The initial input is always a text string like this:

$text = "a,b,c,d,,,e,a,b,c,d,f,g,"; //Note the comma at the end

Then I get the unique array values:

$arrText = array_unique(explode(',',rtrim($text,',')));

Then I count the duplicate values in the array (excluding the empty ones):

$cntText = array_count_values(array_filter(explode(',', $text)));

And finally I echo the array values and their count with a loop inside a loop:

foreach($arrText as $text){
       echo $text;
       foreach($cntText as $cnt_text=>$count){
              if($cnt_text == $text){
                    echo " (".$count.")";
              }
}

I am wondering if there is a better way to output the unique values and their count without using a loop inside a loop.

Currently I have chosen this approach because:

  1. My input is always a text string
  2. The text string contains empty values and has a comma at the end
  3. I need to echo only non empty values

Let me know your expert advices!


Solution

  • You can write your code to print the values a lot shorter (Also I wrote other things a bit shorter):

    You don't need rtrim() or array_unique(), you only need explode() and with array_filter() you take care of the empty values. Then just use array_count_values() and loop through the values.

    <?php
    
        $text = "a,b,c,d,,,e,a,b,c,d,f,g,";
        $filtered = array_filter(explode(",", $text));
        $countes = array_count_values($filtered);
    
        foreach($countes as $k => $v)
            echo "$k ($v)";
    
    ?>
    

    output:

    a (2)b (2)c (2)d (2)e (1)f (1)g (1)