Michael Bisgaard Michael Bisgaard - 7 months ago 9
PHP Question

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));
?>

Answer

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++;
}