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 gkornbluth - April 8, 2022 - edited: April 8, 2022

Hi Tom,

There's a simple code example in my CMSB Cookbook that explains one method that drops the trailing comma in a series. It should point you in the right direction.

http://www.thecmsbcookbook.com/recipedetail.php?REMOVE-THE-TRAILING-COMMA-AFTER-LAST-IMAGE-IN-A-SERIES-355

You can get a 3 month trial subscription to the CMSB Cookbook using the link below.

Hope that helps,

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

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 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