I have this code that should display a list of values from an array followed by a comma and space! However I don't want the last one to have a comma and space after it.
So for example I want tag1, tag2, tag3
instead of tag1, tag2, tag3,
This is my code:
<?php $terms = get_the_terms( $the_post->ID, 'posts_tags' );
foreach ( $terms as $term ) {
echo $term->name;echo ", ";
} ?>
The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.
The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.
Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.
Use the explode function.
$output = array();
foreach($terms as $term){
$output[] = $term->name;
}
echo implode(', ', $output);
It´s an build in php feature called implode -> http://php.net/manual/function.implode.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With