Chris Haugen
Chris Haugen

Reputation: 817

Understanding php loop behaviors

I have a foreach loop and want to list out all the items in an array. The behavior is straightforward, and works like this:

 $posttags = get_the_tags();
        if ($posttags) {
          foreach($posttags as $tag) {
            $tagnames = $tag->name . ', ' ;
            echo $tagnames; 
        }
    }

this code posts the following string: adenosine, blood pressure, Caffeine, cocaine, heart, neurotransmitters, spiders, web

which is every tag name in the array.

However, I would like to use this string outside of the foreach loop, however whenever I do echo $tagnames; outside of thee foreach loop, like this:

    $posttags = get_the_tags();
        if ($posttags) {
          foreach($posttags as $tag) {
            $tagnames = $tag->name . ', ' ; 
        }
      }    

echo $tagnames;

then only the last tag which is web is echo'd. Why is this? and how can I use the full string outside of the foreach loop?

Upvotes: 0

Views: 36

Answers (1)

borracciaBlu
borracciaBlu

Reputation: 4225

What you have to do is initialise an empty variable out of the loop and then concatenate the tags using the .= syntax.

$tagnames = '';
$posttags = get_the_tags();
if ($posttags) {
    foreach($posttags as $tag) {
        $tagnames .= $tag->name . ', ' ; 
    }
}    

echo $tagnames;

Upvotes: 1

Related Questions