Question

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
a and b
a, b and c

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

<?php
 $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'));
 render_array_as_serial_comma(array('a', 'b'));
 render_array_as_serial_comma(array('a', 'b', 'c'));
 ?>
Was it helpful?

Solution

I think you forgot the echo :)

<?php
$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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top