Jump to content

[SOLVED] How to check end of foreach loop?


olli460

Recommended Posts

Hello,

 

Ive got the following code

 

  $tags = explode(',', $tag_str);

    foreach ($tags as $tag)
    {
        
        $tag = trim($tag);
        echo "<a href=\"/search/$tag\">$tag</a>, ";
    }

 

It display a list of tags like one, two, three, four,

 

But it always puts a commer for the last tag, Is there a way to tell that its the last statment it has to echo and not display a commer on the last echo?

 

Thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/175354-solved-how-to-check-end-of-foreach-loop/
Share on other sites

You could use:

 

  $tags = explode(',', $tag_str);

    foreach ($tags as $key => $tag)
    {
       
        $tag = trim($tag);
        echo "<a href=\"/search/$tag\">$tag</a>, ";

        if (($key +1) == count($tags))
        {
             // do something different
        }
    }

Here is also two ways to achieve that not to print the last comma.

 

<?php
$tag_str = 'one,two,three';
$tags = explode(',', $tag_str);
foreach ($tags as $key => $tag)
{
$tag = trim($tag);
$tags[$key] = '<a href="/search/'.$tag.'">'.$tag.'</a>';
}

$tags = implode(',', $tags);
echo $tags;

 

or..

 

<?php
$tag_str = 'one,two,three';
$tags = explode(',', $tag_str);
$tag_str = '';
foreach ($tags as $tag)
{      
$tag = trim($tag);
$tag_str .= "<a href=\"/search/$tag\">$tag</a>, ";
}
echo substr($tag_str, 0, -2);

Sorry, missed the comma part. Rather than echo'in straight out, store the output in a variable and rtrim the end text off:

 

  $tags = explode(',', $tag_str);

    foreach ($tags as $tag)
    {
        $tag = trim($tag);
        $output .= '<a href="/search/'.$tag.'">'.$tag.'</a>, ';
    }

    $output = rtrim($output, ', ');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.