Jump to content

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, ', ');

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.