0

I am trying to remove the last comma(,) from foreach loop in php with the following code

<?php

foreach ($snippet_tags as $tag_data) {
    $tags_id = $tag_data->tag_id;
    $tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
    $tag_name=$tagsdata[0]->tag_name;
?>

<a href="<?= base_url() ?>tags/<?php echo $tag_name; ?>"><?php echo $tag_name; ?></a> ,       

<?php } 
?> 

Right I am getting result like

Hello, How, sam,

But i wants to remove the last comma

Upasana Chauhan
  • 948
  • 1
  • 11
  • 32

2 Answers2

1

By placing the HTML in a simple string variable and then using rtrim() on the resulting string before outputting it this should remove the final , from the string

<?php
$out = '';

foreach ($snippet_tags as $tag_data) {
    $tags_id = $tag_data->tag_id;
    $tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
    $tag_name=$tagsdata[0]->tag_name;

    // move inside loop and amend to place in a simple string var
    $out .= '<a href="' . base_url() . 'tags/' . $tag_name . '">' . $tag_name . '</a>,';
?>

echo rtrim($out, ',');
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

You can also use the following code -

<?php
$numItems = count($snippet_tags);
$i = 0;

foreach ($snippet_tags as $tag_data) {
   $tags_id = $tag_data->tag_id;
   $tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
   $tag_name=$tagsdata[0]->tag_name;
?>

if(++$i === $numItems) 
   echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a>";
else echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a> ,";     

<?php 
} 
?>