Remove "," at end of foreach loop

I've created a loop to list a set of meta values. I've been able to apply a class to the last item in the list, but I'd like to remove the "," at the end of the last value. Any help would be much appreciated.

<?php $count = count($subcategory); $num = 0; ?>
    <?php foreach ($subcategory as $subcategory): ?>
        <p 
            <?php if($num == $count-1){ ?> 
                class="subcategory-item subcategory-last-item inline-block" 
            <?php } ?> 

            class="inline-block subcategory-item"> <?php echo $subcategory;?>,</p>
    <?php $num++ ?>
<?php endforeach; ?>

I may be taking an incorrect route by worrying about adding a class to the last item. If I can remove the "," from the last item I'll be happy.

Answers


Here's a quick rewrite which may lead you to a solution:

<?php $count = count($subcategories); $num = 0; ?>
<?php $classes = 'inline-block subcategory-item'; ?>
<?php foreach ($subcategories as $subcategory): ?>
    <p class="<?=$classes.($num==$count-1?' subcategory-last-item':'')?>">
        <?php echo $subcategory;?>
        <?php if ($num<$count-1): ?>
            ,
        <?php endif; ?>
    </p>
    <?php $num++ ?>
<?php endforeach; ?>

Need Your Help

Create an encrypted zip archive with PHP

php encryption zip

I am searching for a way to encrypt a .txt file into a zip, but in a secure password protected way. My goal is to email this file to me, without anyone being able to read the content of the attachm...

HtmlAttributes in Extension Method

c# asp.net-mvc razor extension-methods asp.net-mvc-5

I'm using MVC 5 and I'm trying to write some Bootstrap extention methods. My goal is to 'overwrite' the Html.ActionLink method with Html.BootstrapLinkButton. The BootstrapLinkButton method should