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:
- My input is always a text string
- The text string contains empty values and has a comma at the end
- I need to echo only non empty values
Let me know your expert advices!