A
A
Alex Mirgorodskiy2017-09-27 15:46:25
PHP
Alex Mirgorodskiy, 2017-09-27 15:46:25

How to trim comma at the end of terms?

Hello everyone, a typical task, I can’t figure out how to do it simply.
There is an array of tags that need to be displayed, each separately (with its own id and name). Well, separated by commas, of course. I do so

<?php $tags_c = count($new->tags); if ($tags_c == 0): ?>

            <span >Разное</span>


        <?php else: ?>

            <?php foreach ($new->tags as $tag):?>

                <span  data-id = "<?= $tag->id ?>"><?= $tag->name ?>,</span>

            <?php endforeach; ?>

        <?php endif; ?>

It naturally gives out like this:
ROBOTICS, QUADROCOPTERS,
How to remove a comma at the end of the last hashtag in every news.
I googled, but there are only arrays or one element, trim, slice and the like, how to apply them correctly in my case? tried like this:
var last = $('.tags_news').find('span:last');
   last.substring(0,last.length - 1);

In the alert, it displays as it should, but the comma does not disappear on the page for all the news, what should I do? in a cycle to do it or did not get there at all?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Samir Kurbanov, 2019-06-16
@kurbanov_samir

1. Quite
2. It’s easier to store json configs in a string format in the database
3. You can store each widget/widget parameter in a table as a separate attribute (column), but in my opinion this option is trashier

I
Igor Koch, 2017-09-27
@AlexWeb6667

Isn't it easier to do it right away in php?
The expression will supply a comma everywhere except the last, but you need to initialize the index ($i) outside of the foreach

<?php $i = 0; ?>
<?php foreach ($new->tags as $tag):?>
  <span  data-id = "<?= $tag->id ?>"><?= $tag->name ?><?=count($new->tags) != ++$i ? "," : ""?></span>
<?php endforeach; ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question