I have a simple function that displays values followed by a comma.
if ( $hasCoAuthors ) :
foreach ( $co_authors as $co_author ) :
$coAuthorDisplayName = $co_author->display_name;
$coAuthor = '<span class="co-author">' . $coAuthorDisplayName . '</span>, ';
echo $coAuthor;
endforeach;
endif;
How to get the last value to remove the comma from it?
I added this function:
function endKey( $array ) {
end( $array );
return key( $array );
}
Then I added this in my function:
if ( endKey( $co_authors ) ) :
$coAuthor = '<span class="co-author">' . $coAuthorDisplayName . '</span>';
endif;
But it doesn't work, it removes commas from all values.
You are printing value each time which is unnecessay, concat them into one string variable then print it once loop ended by using rtrim() to remove last comma.
You need to correct loop code like below:
if ( $hasCoAuthors ) :
$coAuthor = '';
foreach ( $co_authors as $co_author ) :
$coAuthor .= '<span class="co-author">' . $co_author->display_name . '</span>, ';
endforeach;
echo rtrim($coAuthor, ',');
endif;
Build the html in a string, then trim the final comma using trim() before echoing it once when the loop is complete.
if ( $hasCoAuthors ) :
$coAuthor = '';
foreach ( $co_authors as $co_author ) :
$coAuthor .= '<span class="co-author">' . $co_author->display_name . '</span>, ';
endforeach;
echo rtrim($coAuthor, ',');
endif;
Or as @CBroe suggests
if ( $hasCoAuthors ) :
$coAuthor = '';
foreach ( $co_authors as $k => $co_author ) :
if ($k > 0 ) {
$coAuthor .= ','
}
$coAuthor .= '<span class="co-author">' . $co_author->display_name . '</span>';
endforeach;
echo $coAuthor;
endif;
If keys are numeric (0, 1, 2, etc.), you can use simply this code to add , to 2nd and others.
if ( $hasCoAuthors ) :
foreach ( $co_authors as $key => $co_author ) :
$coAuthor = '';
if ($key > 0) {
$coAuthor = ', ';
}
$coAuthorDisplayName = $co_author->display_name;
$coAuthor .= '<span class="co-author">' . $coAuthorDisplayName . '</span>, ';
echo $coAuthor;
endforeach;
endif;
The second way is to put values into array and use implode.
if ( $hasCoAuthors ) :
$coAuthors = [];
foreach ( $co_authors as $key => $co_author ) :
$coAuthorDisplayName = $co_author->display_name;
$coAuthors[] = '<span class="co-author">' . $coAuthorDisplayName . '</span>';
endforeach;
echo implode(', ', $coAuthors);
endif;