Talk #3: PHP – Comma Separated List from Array

After we discussed how to create a comma separated list in twig last week, this week I will show you how to do the same in plain PHP.

Simple Comma Separated List in PHP without trailing comma

The easiest way to get a String in PHP from the elements of an Array joined by some character is to use the implode function:

$my_array = array('string1', 'string2', 'string3');
$comma_separated_list = implode(", ", $my_array);
// $comma_separated_list now holds the value "string1, string2, string3" from the array $my_array

As you can see, implode takes an array and returns a string containing its elements separated by a character of your choice which in this example is a comma.

Join complex Strings with Comma in PHP

Lets say we want to create a list of links and this list should be separated by commas.
It is easiest to just create the list and then remove the trailing comma at the end:

$my_array = array('link1', 'link2', 'link3');
$output = '';
foreach ($my_array as $link) {
    $output .= '<a href="' . $link . '">' . $link . '</a>' . ', ';
// remove last two characters (', '):
$output = substr($output, 0, strlen($output) - 2);
// $output now holds the value '<a href="link1">link1</a>, <a href="link2">link2</a>, <a href="link3">link3</a>'

Related Posts:

Leave a Reply

Your email address will not be published.