Counting duplicate tags in a string of many tags I have a photo list page where each photo has multiple tags (as spaced words). I'm trying to display most of the tags on the page after:


Removing duplicate tags
Sorting tags by having most occurring tags first


The code looks like this: 

$tags1 = "red blue green yellow colors";
$tags2 = "blue green grass tree garden";    
$tags3 = "pink blue colors paint sky"

addTags($tags1);
addTags($tags2);
addTags($tags3);
echo (processTags());

private $tagsArray;
public function addTags($param) {
    if($param == ""){ // no tags
        return;
    }
    $explode = explode(" ",$param);
    $this-&gt;tagsArray = array_merge($this-&gt;tagsArray, $explode);
}

private function processTags(){
    $processedTags = array_count_values($this-&gt;tagsArray);
    arsort($processedTags);
    $count = 0;
    foreach($processedTags as $tag =&gt; $value) { 
        if(++$count&gt;50) break; // don't print more than 50 tags
        $output .= "&lt;a href=\"/tags/$tag\"&gt;$tag&lt;/a&gt;";
    }
    return $output;
}


Each photo can have dozens of tags and there can be hundreds of tags total. Is there any way to improve the code to make it more efficient? Could it be done with less code? The above code works just fine, but I'm just curious to know if there is a better way to go about it.
I has been a long time since I used PHP, but what you want are multisets that are basically sets with a value -> number-of-occurrences mapping. I believe you can accomplish this in PHP via associative arrays as below:

$tags1 = "red blue green yellow colors blue red green yellow yellow";

function addTags($param) {

    // tagsArray should be a global variable
    // but put as local variable for illustration only
    $tagsArray = array();

    if($param == ""){ // no tags
        return;
    }
    $explode = explode(" ",$param);

    foreach ($explode as $value) {
       $val = 0;
       if (array_key_exists($value, $tagsArray)) {
          $val = $tagsArray[$value];          
       }

       $tagsArray[$value] = 1 + $val;
    }

    // sort the array
    arsort($tagsArray);

    // for illustration purposes only
    foreach ($tagsArray as $key =&gt; $value) {
       echo $key.':'.$value.', ';
    }
}

addTags($tags1);