Use rtrim:
$cats = '';
foreach((get_the_category()) as $category) {
$cats .= $category->cat_name . ', ';
}
echo rtrim($cats, ', ');
Вопрос
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, ',');