Search code examples
phpregexdynamic-datastrstr

php only get the first occurrence of a word from an array


I have an array of tags that I'm pulling from a database, I am exporting the tags out into a tag cloud. I'm stuck on getting only the first instance of the word. For example:

$string = "test,test,tag,tag2,tag3";

$getTags = explode("," , $string);
  foreach ($getTags as $tag ){
     echo($tag);
   }

This would output the test tag twice. at first i thought i could use stristr to do something like:

  foreach ($getTags as $tag ){
      $tag= stristr($tag , $tag); 
        echo($tag);
   }

This is obviously silly logic and doesn't work, stristr seems to only replace the first occurrence so something like "test 123" would only get rid of the "test" and would return "123" I've seen this can also be done with regex but I haven't found a dynamic exmaple of that.

Thanks,
Brooke

Edit: unique_array() works if I'm using a static string but won't work with the data from the database because I'm using a while loop to get each rows data.

    $getTag_data = mysql_query("SELECT tags FROM `news_data`");
if ($getTag_data)
{

   while ($rowTags = mysql_fetch_assoc($getTag_data))
   {
     $getTags = array_unique(explode("," , $rowTags['tags']));
        foreach ($getTags as $tag ){
        echo ($tag);
      }
   }
}

Solution

  • I'm assuming that each row in your table contains more than one tag, separated by coma, like this:

    Row0: php, regex, stackoverflow
    Row1: php, variables, scope
    Row2: c#, regex
    

    If that's the case, try this:

    $getTag_data = mysql_query("SELECT tags FROM `news_data`");
    
    //fetch all the tags you found and place it into an array (with duplicated entries)
    $getTags = array();
    if ($getTag_data) {
       while ($row = mysql_fetch_assoc($getTag_data)) {
         array_merge($getTags, explode("," , $row['tags']);
       }
    }
    
    //clean up duplicity
    $getTags = array_unique($getTags);
    
    //display
    foreach ($getTags as $tag ) {
       echo ($tag);
    }
    

    I'd point out that this is not efficient.

    Another option (already mentioned here) would be to use the tags as array keys, with the advantage of being able to count them easily.
    You could do it like this:

    $getTag_data = mysql_query("SELECT tags FROM `news_data`");
    
    $getTags = array();
    if ($getTag_data) {
       while ($row = mysql_fetch_assoc($getTag_data)) {
         $tags = explode("," , $row['tags']);
         foreach($tags as $t) {
           $getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
         }
       }
    }
    
    //display
    foreach ($getTags as $tag => $count) {
       echo "$tag ($count times)";
    }
    
    • please keep in mind none of this code was tested, it's just so you get the idea.