Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Separate array with commas [duplicate]

Tags:

arrays

php

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 ", ";
                                } ?>
like image 729
Cameron Avatar asked Mar 23 '11 15:03

Cameron


People also ask

How do you separate an array with a comma?

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.

How to store comma separated values in array PHP?

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.

How do you store comma separated values in an array?

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.

How to get comma separated values from database in PHP?

Use the explode function.


2 Answers

$output = array();
foreach($terms as $term){
  $output[] = $term->name;
}
echo implode(', ', $output);
like image 135
Rocket Hazmat Avatar answered Oct 01 '22 00:10

Rocket Hazmat


It´s an build in php feature called implode -> http://php.net/manual/function.implode.php

like image 35
Tobias Avatar answered Oct 01 '22 01:10

Tobias