Search code examples
phpmysqlarray-push

How do i merge matching strings in an array?


Hi I currently have this code that retrieves the tags from each Image in the Database. The tags are seperated by commas. I place each set of tags on the end of the array. Now I want to create an array of the tags retrieved but merge any duplications.

    function get_tags()
{
    $tag_array = array();
    $query = mysql_query("
    SELECT tags 
    FROM gallery_image
    ");

    while($row = mysql_fetch_assoc($query))
    {
        $tags = $row['tags'];
        $tag_array[] = $tags;

    }

    echo $tag_array[0] . '<br>' . $tag_array[1] . '<br>' .$tag_array[2];
}

Solution

  • You question is not very clear but array_unique may be what you need?

    function get_tags()
    {
      $query = mysql_query('SELECT tags '.
                           'FROM gallery_image');
      $tag_array = array();
      while($row = mysql_fetch_assoc($query))
        $tag_array = array_merge($tag_array, explode(',', $row['tags']));
    
      return array_unique($tag_array);
    }