سؤال

im using

<?php
    foreach((get_the_category()) as $category) {
        echo $category->cat_name . ', ';
    }
?>

now this obviously outputs a comma at the end of each "category" how would i go about emoving the comma from the last item in the list?

هل كانت مفيدة؟

المحلول

Use rtrim:

$cats = '';
foreach((get_the_category()) as $category) {
    $cats .= $category->cat_name . ', ';
}
echo rtrim($cats, ', ');

نصائح أخرى

Here is another way to do it, using the join function-

echo join(",",array_map(function($category){return $category->cat_name;}, get_the_category()));

You can try this:

$categories = array();
foreach(get_the_category() as $category) {
    $categories[] = $category->cat_name;
}

echo implode($categories, ',');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top