Ask for help about comma to every item but last one

5 posts by 4 authors in: Forums > CMS Builder
Last Post: April 17, 2022   (RSS)

By Tom - April 8, 2022

Hello,

Below is my code.

<?php $movie_cat = array_combine($listing['movie_cat:values'], $listing['movie_cat:labels']); ?>
<?php foreach ($movie_cat as $movie_catNum => $movie_catName): ?>
<a href="listings.php?movie_cat=<?php echo $movie_catNum;?>"><?php echo implode( ', ', $listing['movie_cat:labels'] ); ?></a>
<?php endforeach ?>

What I intend to do is output TEST1, TEST2, TEST3 instead of Test1 Test2 Test3

However it returns

Test1,Test2,Test3 Test1,Test2,Test3 Test1,Test2,Test3

Could you please take a look on it.

Thank You

By daniel - April 8, 2022

Hi Tom,

For this kind of loop, it looks like you'll want to echo the $movie_catName variable, rather than using the implode function which is displaying all categories on every loop. I would then add a "count" variable to track which loop you're on, to check if you need to add a comma. Something like this should work:

<?php $movie_cat = array_combine($listing['movie_cat:values'], $listing['movie_cat:labels']); ?>
<?php $count = 0; ?>
<?php foreach ($movie_cat as $movie_catNum => $movie_catName): ?>
<?php
  if ($count++ > 0) {
    echo ', ';
  }
?><a href="listings.php?movie_cat=<?php echo $movie_catNum;?>"><?php echo $movie_catName; ?></a>
<?php endforeach ?>

You can also check out Jerry's CMSB Cookbook for other examples and ideas!

Thanks,

Daniel
Technical Lead
interactivetools.com

By Tom - April 9, 2022

Hello,

This is perfect.

Thank You

By kitsguru - April 17, 2022

You can also use the trim function on a string and supply a comma as the second parameter:

trim("test, test1, test2,", ",") 

will yield:

test, test1, test2

You can pass multiple characters in the second parameter and all will be remove both leading and trailing.

Jeff Shields