Print Array Without Trailing Commas In PHP

I have previously talked about Removing commas from the end of strings, but it is also possible to use the implode() function to do the same sort of thing.

implode() takes two parameters, the separator and the array, and returns a string with each array item separated with the separator. The following example shows how this function works.

$array = array(1,2,3,4,5,6);
$list = implode(',', $array);

The $list variable will now contain the string "1,2,3,4,5,6". However, things tend to become messy again when you have an array with empty items in it.

$array = array(1,2,3,4,5,6,'','','');
$list = implode(',', $array);

The $list variable will now contain the string "1,2,3,4,5,6,,". So to solve this issue we need to use the array_filter() function to clear out any blank array items before passing the output to the implode() function. The following example shows this in action.

$array = array(1,2,3,4,5,6,'','','');
$list = implode(',', array_filter($array));

The $list variable will now contain the string "1,2,3,4,5,6", which is the string we are looking for.

Comments

Thanks.

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
7 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.