Remove trailing comma from Tag list

Heya! :wave: I’m struggling to find a way to remove a trailing comma from the end of my filter list. Currently its outputting like this:

tag1, tag2, tag3,

But i’d like to to display as:

tag1, tag2, tag3

I’ve tried using $filters->last()); but I understand that only works for Structure and Collections… Is there some way to detect that this is the last tag in the array and remove the comma?

    <nav class="filter">
      <a href="<?= $site->url() ?>">All,</a>
      <?php foreach ($filters as $filter): ?>
        <a href="<?= $site->url() ?>?filter=<?= $filter ?>">
        <?php if($filter != $filters->last()): ?>
          <?= $filter ?></a>,
        <?php else: ?>
          <?= $filter ?></a>
        <?php endif ?>
      <?php endforeach ?>

Any help would be greatly appreciated!

You could use a counter variable as a helper.

Personally, I’d prefer to add the comma via CSS.

This is a common task in programming: You want to join the elements of a given array to a string, separated by another arbitrary string. Additionally you want to manipulate all the elements of the array by the same way.

The first task is done with PHP’s implode function, the second with array_map. In the end, your foreach loop can be replaced with:


function myurl($value) {
  return '<a href="'.$site->url().'?filter='.$value.'">'.$value.'</a>';

echo implode(",",array_map('myurl',$filters));


or, if you like to make only one statement:

<?= implode(",",array_map(function($value) { return '<a href="'.$site->url().'?filter='.$value.'">'.$value.'</a>'; },$filters)); ?>

You cannot use $site here without a use statement or the site() helper:

<?= implode(",",array_map(function($value) use($site) { 
return '<a href="'.$site->url().'?filter='.$value.'">'.$value.'</a>'; },$filters)); ?>`

Also, I think it would be cleaner to use Kirby’s Html class (and you don’t need the use statement with PHP 7.4 arrow functions:

<?= implode(', ', array_map(fn ($value) => Html::a(url(null, ['query' => ['filter' => $value]]), $value), $filters));?>
1 Like