4.9. Printing an Array with Commas
Problem
You want to print out an array with commas separating the elements and with an “and” before the last element if there are more than two elements in the array.
Solution
Use the pc_array_to_comma_string( )
function shown in Example 4-1, which returns the correct string.
Example 4-1. pc_array_to_comma_string( )
function pc_array_to_comma_string($array) {
switch (count($array)) {
case 0:
return '';
case 1:
return reset($array);
case 2:
return join(' and ', $array);
default:
$last = array_pop($array);
return join(', ', $array) . ", and $last";
}
}Discussion
If you have a list of items to print, it’s useful to print them in a grammatically correct fashion. It looks awkward to display text like this:
$thundercats = array('Lion-O', 'Panthro', 'Tygra', 'Cheetara', 'Snarf');
print 'ThunderCat good guys include ' . join(', ', $thundercats) . '.';
ThunderCat good guys include Lion-O, Panthro, Tygra, Cheetara, Snarf.This implementation of this function isn’t
completely straightforward, since we want
pc_array_to_comma_string( ) to work with all
arrays, not just numeric ones beginning at 0. If
restricted only to that subset, for an array of size one, you return
$array[0]. But, if the array
doesn’t begin at 0,
$array[0] is empty. So, you can use the fact that
reset( )
, which resets an
array’s internal pointer, also returns the value of
the first array element.
For similar reasons, you call array_pop( )
to grab the end element, instead of assuming it’s ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access