0

Very new to Wordpress and web design. I have this function for separating categories with a comma ",". But it also adds the comma after the last category. Making it look like this:

Category1, Category2, Category3,

When I want it like this:

Category1, Category2, Category3

Without the last comma behind Category3

How can I stop the function from adding the last comma?

<?php
    $category_detail = get_the_category($post->ID); //$post->ID
    foreach ($category_detail as $cd) {
        echo $cd->cat_name . ', ';
    }
    ?>

Regards

  • Check this one https://stackoverflow.com/questions/1070244/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop – Doğuş Jul 31 '21 at 19:49
  • Just use `implode()` – Jaquarh Jul 31 '21 at 19:58
  • Does this answer your question? [How to determine the first and last iteration in a foreach loop?](https://stackoverflow.com/questions/1070244/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop) – Abdelrahman Hatem Aug 01 '21 at 01:09

2 Answers2

0

There is many approaches to splitting arrays values.

Indeed you could achieve it via a foreach loop, by counting iterations.

$category = get_the_category($post->ID);
$i = 0;
foreach ($categories as $category) {
  $i++;
  echo $category->cat_name;
  if ($i < count($items))
    echo ', ';
};

Tho a more concise approach would be using the implode() native function:

$categories = get_the_category($post->ID);
echo implode(', ', $categories);
amarinediary
  • 3,600
  • 3
  • 23
  • 30
0

With this foreach loop you are actually converting an array into string. Thus, if it is more understandable to use, you could just erase the last char like this:

<?php
    $str=''; //single quotes
    $category_detail = get_the_category($post->ID); //$post->ID
    foreach ($category_detail as $cd) {
        $str .= $cd->cat_name . ', ';
    }
echo substr($str, 0, -1);
    ?>