lopes_andre Posted January 30, 2010 Share Posted January 30, 2010 Hi, I have a problem listing data from database. I need to list data from a database and the results should be separated by ',', but I need a way to not show the ',' in the last cicle of the foreach. My code is this: <?php foreach ($result4 as $row4): ?> <?php echo $row4->n_lingua ; ?>, <?php endforeach; ?> The result of this is: "Portuguese, English," The question: How can I remove the last "," from the cicle? Best Regards, Quote Link to comment https://forums.phpfreaks.com/topic/190375-last-foreach-cicle-how-to-know/ Share on other sites More sharing options...
wildteen88 Posted January 30, 2010 Share Posted January 30, 2010 You may want to use implode instead. <?php foreach ($result4 as $row4) $rows[] = $row4->n_lingua; echo implode(',', $rows); ?> Quote Link to comment https://forums.phpfreaks.com/topic/190375-last-foreach-cicle-how-to-know/#findComment-1004293 Share on other sites More sharing options...
lopes_andre Posted January 30, 2010 Author Share Posted January 30, 2010 Thanks for the reply, It should return "Ingles, Espanhol, Portugues" but is returning "Ingles Ingles, Espanhol Ingles, Espanhol, Portugues" The code is: <?php foreach ($result4 as $row4): ?> <?php $rows[] = $row4->n_lingua ; ?> <?php echo implode(', ', $rows); ?> <?php endforeach; ?> What should be wrong here? Best Regards, Quote Link to comment https://forums.phpfreaks.com/topic/190375-last-foreach-cicle-how-to-know/#findComment-1004300 Share on other sites More sharing options...
lopes_andre Posted January 30, 2010 Author Share Posted January 30, 2010 Sorry, It is working now: <?php foreach ($result4 as $row4): ?> <?php $rows[] = $row4->n_lingua ; ?> <?php endforeach; ?> <?php echo implode(', ', $rows); ?> Thanks for the help. Best Regards, Quote Link to comment https://forums.phpfreaks.com/topic/190375-last-foreach-cicle-how-to-know/#findComment-1004304 Share on other sites More sharing options...
teamatomic Posted January 30, 2010 Share Posted January 30, 2010 Is the foreach you showed us nested inside another foreach? if so eliminate the nested foreach and use the implode on the $resultX. HTH Teamatomic Quote Link to comment https://forums.phpfreaks.com/topic/190375-last-foreach-cicle-how-to-know/#findComment-1004305 Share on other sites More sharing options...
dpacmittal Posted January 30, 2010 Share Posted January 30, 2010 Thats a nice way. I always do: preg_match('!(.*),!', $text, $matches); $text = $matches[1]; I'll keep this method in mind too. Quote Link to comment https://forums.phpfreaks.com/topic/190375-last-foreach-cicle-how-to-know/#findComment-1004306 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.