-1

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.

3
  • 2
    Are you sure that each tag is the same case, string length, etc... meaing, are the string exactly the same character for character? Might want to try setting all values to lowercase before trying array_unique. Commented Aug 5, 2010 at 21:20
  • 1
    At what point did you try array_unique? Commented Aug 5, 2010 at 21:30
  • We cannot reproduce your error and your code does not include your implementation of array_unique(). This question is Unclear, No-Repro, and Needs Debugging Details. Commented Jan 18 at 20:51

2 Answers 2

4

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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>";
}

1 Comment

$my_array should be $tmp_array shouldn't it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.