etrader Posted September 2, 2011 Share Posted September 2, 2011 I use foreach to echo a list of tags come out of an array as foreach ($array as $tag) { echo "$tag,"; } This produces "tag1,tag2,tag3,". The problem is the last ",". How to tell the foreach loop to avoid including "," after the last sequence? Link to comment https://forums.phpfreaks.com/topic/246267-how-to-avoid-an-action-in-the-last-cycle-of-a-foreach-loop/ Share on other sites More sharing options...
Pikachu2000 Posted September 2, 2011 Share Posted September 2, 2011 The easiest way in that scenario would be to use implode() instead of a loop. echo implode(',', $array); Link to comment https://forums.phpfreaks.com/topic/246267-how-to-avoid-an-action-in-the-last-cycle-of-a-foreach-loop/#findComment-1264690 Share on other sites More sharing options...
AyKay47 Posted September 2, 2011 Share Posted September 2, 2011 im thinking something along the lines of this.. foreach ($array as $tag) { if(end($array) == $tag){ echo $tag; }else{ echo "$tag,"; } } Edit I like the implode method here Link to comment https://forums.phpfreaks.com/topic/246267-how-to-avoid-an-action-in-the-last-cycle-of-a-foreach-loop/#findComment-1264691 Share on other sites More sharing options...
cyberRobot Posted September 2, 2011 Share Posted September 2, 2011 There are many ways, but my preferred method is: $firstTime = true; foreach ($array as $tag) { if($firstTime) { echo "$tag"; firstTime = false; } else { echo ",$tag"; } } Link to comment https://forums.phpfreaks.com/topic/246267-how-to-avoid-an-action-in-the-last-cycle-of-a-foreach-loop/#findComment-1264692 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.