문제

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'));
 ?>
도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top