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 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 } } 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); 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, ', '); 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 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
Archived
This topic is now archived and is closed to further replies.