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'));
 ?>
3
  • 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, 2014 at 22:24
  • $variables['items'] — This variable won't be available inside your function. I suggest you enable error reporting to find similar errors. Apr 15, 2014 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, 2014 at 22:44

1 Answer 1

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

2
  • There is every possibility that hat is what i did. To quote Homer, DUH!
    – Chezshire
    Apr 16, 2014 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, 2014 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.