Hi
I’ve got a structure field that I would like to have a comma after each entry. But I don’t want the last entry to have a comma.
So my code looks like this:
<?php foreach($site->ads()->toStructure() as $ad): ?>
<?php echo $ad->adimg() ?>,
<?php endforeach ?>
I would like my output to look like:
adimg1, adimg2, adimg3
But the best I can do is:
adimg1, adimg2, adimg3 ,
I just can’t figure out if there’s a kirby-based solution or not. Or do I have to do some straight-up php?
thanks! 
You can use the $collection->last()
method to check if the item is (or rather is not) the last item of the collection.
BTW: When posting blocks of code, it helps to make them more readable if you enclose them within three backticks at the beginning and the end of such a block, Thank you 
Quick thought:
<?php
$adimgs = array_column($site->ads()->yaml(), 'adimg');
echo implode(',', $adimgs);
?>
So I have tried using last() on the structure field. But I can’t make it work:
<?php foreach($site->ads()->toStructure() as $ad): ?>
<p>
<?php if($ad->adimg() != $ad->adimg()->last()): ?>
<?php echo $ad->adimg() ?>,
<?php elseif: ?>
<?php echo $ad->adimg() ?>
<?php endif ?>
</p>
<?php endforeach ?>
Also, sorry about the lack of code block. I’ve added the triple-backticks .
Thanks! 
Not having much luck with this approach either. Perhaps I’ve been staring at this too long today…
Try this, not tested, though:
<?php
$ads = $site->ads()->toStructure();
foreach($ads as $ad): ?>
<p>
<?php if($ad != $ads->last()): ?>
<?php echo $ad->adimg() ?>,
<?php else: ?>
<?php echo $ad->adimg() ?>
<?php endif ?>
</p>
<?php endforeach ?>
BTW: If you use elseif, you need a second condition, which is not needed here.
1 Like
That’s it. 
thanks so much. I was staring at the for so long I didn’t even notice the elseif.