Printing an Array with Commas

The way to print out an array with commas separating the elements.

Posted on April 18, 2016 in PHP

You want to print out an array with commas separating the elements and with an and before the last element if there are more than two elements in the array.

Solution

Using the following method to achieve the goal.


function array_to_comma_string($array) {
    switch(count($array)) {
        case 0:
            return '';
        case 1:
            return reset($array);
        case 2:
            return join(' and ', $array);
        case 3:
            $last = array_pop($array);
            return join(',  ', $array) . ", and $last";
    }
}

If you can use join(), do; it’s faster. However, join() isn’t very flexible. First, it places a delimiter only between elements, not around them. To wrap elements inside HTML tag and separate them with space, do this:


$left = '<b>';
$right = '</b>';

$html = $left . join("$right $left", $html). $right;


comments powered by Disqus