olli460 Posted September 24, 2009 Share Posted September 24, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/175354-solved-how-to-check-end-of-foreach-loop/ Share on other sites More sharing options...
Adam Posted September 24, 2009 Share Posted September 24, 2009 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 } } Quote Link to comment https://forums.phpfreaks.com/topic/175354-solved-how-to-check-end-of-foreach-loop/#findComment-924076 Share on other sites More sharing options...
TeNDoLLA Posted September 24, 2009 Share Posted September 24, 2009 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); Quote Link to comment https://forums.phpfreaks.com/topic/175354-solved-how-to-check-end-of-foreach-loop/#findComment-924079 Share on other sites More sharing options...
Adam Posted September 24, 2009 Share Posted September 24, 2009 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, ', '); Quote Link to comment https://forums.phpfreaks.com/topic/175354-solved-how-to-check-end-of-foreach-loop/#findComment-924099 Share on other sites More sharing options...
olli460 Posted September 24, 2009 Author Share Posted September 24, 2009 Thanks for the solutions TeNDoLLA & MrAdam Quote Link to comment https://forums.phpfreaks.com/topic/175354-solved-how-to-check-end-of-foreach-loop/#findComment-924102 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.