How to use implode with commas in a PHP array?


I’m trying to see how a serial comma does or doesn’t print in an array. I’ve found several methods that work and am trying to do my own spin on what I’ve seen but mine is not working and I do not know why.

I was hoping the below function would return the result shown below, but it seems to return nothing/nothing happens when I test it. I’ve looked at my formatting, semicolons, etc, and I’m stumped. This is a little beyond me, and very exciting. I’m trying to understand why this does not work and how to make it work as clearly somewhere my logic or understanding is very faulty as nothing happens.

Expected/hoped for result:

a and b
a, b and c

Actual result: < White space/no html render/nada/nothing/zippo >

 $items = array('a','b','c');

 function render_array_as_serial_comma($items) {
 $items = $variables['items'];

 if (count($items) > 1) {
 $last = array_pop($items);
 return implode(', ', $items) . ' and ' . $last;
 return array_pop($items);

 render_array_as_serial_comma(array('a', 'b'));
 render_array_as_serial_comma(array('a', 'b', 'c'));


I think you forgot the echo 🙂

$items = array('a', 'b', 'z');

function render_array_as_serial_comma($items) {
    $final_string = array_pop($items);
    if(count($items) >= 1) {
        $final_string = implode(', ', $items) . ' and ' . $final_string;
    return $final_string;

echo render_array_as_serial_comma($items);

Sample Fiddle

Answered By – user1978142

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published