views:

59

answers:

3

Hey All,
Just wondering if you can help me out.
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:

<?php   
$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. Any help would be greatly appreciated and I thank you in advance for your help!!!

Cheers

+2  A: 

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>";
}
Sarfraz
`$my_array` should be `$tmp_array` shouldn't it?
Amber
@Amber: Sure it should, thanks :)
Sarfraz
+4  A: 

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?

eigenein
A: 

Hey Guys,

Thanks for your help... By after further review I think i am going about this all wrong and need to re-config a few things to make it a little more scalable.

I thank you all for your help!!!

Very much appreciated.

Tek9 :)

Tek9
You should accept one of the answers above as correct even if the original problem doesn't apply to you anymore. They are both technically correct answers to your initial question, and can be useful to others with similar problems.
Ivar Bonsaksen