maddy maddy - 22 days ago 10
PHP Question

remove last comma from string in while loop in php?

I am using while loop to get values from my database and my result is like:

enter image description here

I want to remove comma after last value of loop.

i used code like..

<?php
$cat = get_terms('car_category'); // you can put your custom taxonomy name as place of category.
foreach ($cat as $catVal) {
echo '<b>'.$catVal->name.'</b>';
$postArg = array('post_type'=>'cars','posts_per_page'=>5,'order'=>'desc',
'tax_query' => array(
array(
'taxonomy' => 'car_category',
'field' => 'term_id',
'terms' => $catVal->term_id
)
));

$getPost = new wp_query($postArg);
global $post;

if($getPost->have_posts()){
$str = "";
echo '<div class="yearDiv">';
while ( $getPost->have_posts()):$getPost->the_post();
$str =rtrim($post->post_title, ",");
echo '<span>'.$str.',</span>';
endwhile;
echo '</div>';
}
}
?>


i used rtrim , substr function also for it but comma not removing.

Answer

Take the post titles in an array and Use Implode instead ..

<?php
 $cat = get_terms('car_category'); // you can put your custom taxonomy name as place of category.
        foreach ($cat as $catVal) {
            echo '<b>'.$catVal->name.'</b>';
            $postArg = array('post_type'=>'cars','posts_per_page'=>5,'order'=>'desc',
                              'tax_query' => array(
                                                    array(
                                                        'taxonomy' => 'car_category',
                                                        'field' => 'term_id',
                                                        'terms' => $catVal->term_id
                                                    )
                            ));

            $getPost = new wp_query($postArg);
            global $post;

            if($getPost->have_posts()){
                $str = array();

                    while ( $getPost->have_posts()):$getPost->the_post();
                        $str[] = $post->post_title;

                    endwhile;
            }
            echo '<div class="yearDiv">';
            echo '<span>'.implode(', ', $str).'</span>';
            echo '</div>'
        }
?>
Comments