0

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'));
 ?>
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Chezshire
  • 713
  • 5
  • 13
  • 32
  • Perhaps an `echo` might help.... but your $last will be a problem when there's only one entry in the array – Mark Baker Apr 15 '14 at 22:24
  • `$variables['items']` — This variable won't be available inside your function. I suggest you [enable error reporting](http://stackoverflow.com/a/6575502/1438393) to find similar errors. – Amal Murali Apr 15 '14 at 22:26
  • I was working locally (using MAMP on my mac) which i thought had error handling turned on. But loading it up to my site, I see i have an error message which reads 'Warning: array_pop() expects parameter 1 to be array, null given in fileX.php on line 12 which is 'return array_pop($items);'. I have more to go on now. ' – Chezshire Apr 15 '14 at 22:44

1 Answers1

1

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

user1978142
  • 7,946
  • 3
  • 17
  • 20
  • There is every possibility that hat is what i did. To quote Homer, DUH! – Chezshire Apr 16 '14 at 21:38
  • Thank you, it works. I learned a lot form this including how to turn on and off error notification on a page or my whole site (i went on several learning tangents) – Chezshire Apr 16 '14 at 22:20