How to remove the last comma from a foreach loop in Codeigniter
In my Codeigniter project, I have listed some data using foreach loop. I have added a comma symbol after every line but I want to remove the comma symbol while the loop is last. My code does not work the same. How can I remove the last comma from a foreach loop in Codeigniter?
<?php $name = ""; $listIds = explode(',', $value['ids']); foreach($listIds as $k=>$v) { $CI=&get_instance(); $name .= $CI->getUserNameById($v, true).","; } echo $name; ?>
My Output like Abhishek, ABX, Aliana,
I want to display
Abhishek, ABX, Aliana
To remove the last comma from a foreach loop in Codeigniter, first, define an array variable and push the values into the array variable while it is in the loop. After the end applies PHP implode() method to avoid the last symbol from the string.
As your code example:
<?php $Name = []; $listIds = explode(',', $value['ids']); foreach($listIds as $k=>$v) { $CI=&get_instance(); $Name[] = $CI->getUserNameById($v, true); } echo implode( ', ', $Name); ?>
Output: Abisheak, ABX, Aliana
Question and answer is powered by AnsPress.io