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

15
  • @u_mulder Did you properly check? my question related to the question what you linked? Sep 24, 2019 at 14:42
  • Why wouldn't what @u_mulder suggested work?
    – Script47
    Sep 24, 2019 at 14:43
  • @RiggsFolly Yes, I agreed! Sep 24, 2019 at 14:43
  • @RiggsFolly it's like a hint for OP - use a search.
    – u_mulder
    Sep 24, 2019 at 14:44
  • 1
    easy solution: save your link in a string and then create an array of links then simply use implode(' ,' $links_arr)
    – Umer Abbas
    Sep 24, 2019 at 15:10

2 Answers 2

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, ',');
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 
} 
?> 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.