Tek9
Tek9

Reputation: 9

Remove duplicate values from a flat array

I have a column with rows of tags. In each row, I have each tag separated with a comma and space.

for example: BMW M5, Leather Seats, 24 Inch Wheels, etc.

What I need to do is loop through the array, explode it, and then print the values to the page. So far I have been able to do it; however, it prints the duplicates.

Here is the code I have so far:

$cleanTags = ($row_getTags['tags']);  
$cleanerTags = str_replace(', ', "-", $cleanerTags);  
$tagstr = ($cleanerTags);   
$tags = explode('-', $tagstr);  

foreach ($tags as $tag)  
{   
    echo "<li><a href=\"results.php?search=" . str_replace("&nbsp;", '%20', $tag) . "\" title=\"Find more stuff tagged:&nbsp;" . $tag . "\" class=\"tagLink\">" . $tag . "</a></li>";
}

How can I go about removing duplicates from the array? I've tried array_unique() with no luck.

Upvotes: -1

Views: 5568

Answers (2)

Sarfraz
Sarfraz

Reputation: 382881

If array_unique didn't do the trick (I wonder how you used that), here is one way:

function remove_duplicates(array $array){
  $tmp_array = array();

  foreach($array as $key => $val)  
  {
     if (!in_array($val, $tmp_array))
     {
       $tmp_array[$key]  = $val;
     }
  }

  return $tmp_array;
}

And now your code should be:

$cleanTags = ($row_getTags['tags']);  
$cleanerTags = str_replace(', ',"-",$cleanerTags);  
$tagstr = ($cleanerTags);   
$tags = explode('-',$tagstr);  

// remove duplicates
$tags = remove_duplicates($tags);

foreach($tags as $tag)  
{   
  echo "<li><a href=\"results.php?search=".str_replace("&nbsp;",'%20',$tag)."\" title=\"Find more stuff tagged:&nbsp;".$tag."\" class=\"tagLink\">".$tag."</a></li>";
}

Upvotes: 2

eigenein
eigenein

Reputation: 2200

Normally, array_unique solves your problem. Like this:

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);

So... Can you show how did you try array_unique?

Upvotes: 4

Related Questions