Michael Bisgaard
Michael Bisgaard

Reputation: 3

Problems with dots in the end of tags

I am struggling with this piece of code. I do not want a dot after the last tag, what line do I write so that there is no dot after the last tag?

<?php
    $id = get_sub_field('case_link');
    $posttags = get_the_tags($id);
    $tags = '';

    if ($posttags) {
        foreach ($posttags as $tag) {
            $tags .= $tag->name . ' &middot; ';
        }
    }

    $tags = trim(substr($tags, 0, -2));
?>

Upvotes: 0

Views: 36

Answers (2)

Matt
Matt

Reputation: 1757

add a counter and check if you are on the last iteration, if so add the name without the dot.

$id = get_sub_field('case_link');
$posttags = get_the_tags($id);
$tags = '';
$i = 0;
$len = count($posttags);

foreach ($posttags as $tag) {
    if($i != $len-1) {
        $tags .= $tag->name . ' &middot; ';
    }
    else {
        $tags .= $tag->name;
    }
    $i++;
}

Upvotes: 1

Tushar Gupta
Tushar Gupta

Reputation: 15923

Simply use rTrim() function

rtrim($yourString, 'ChartoRemove');

For your case

rtrim($tags, '&middot;');

Upvotes: 1

Related Questions