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.
Use the pc_array_to_comma_string( )
function shown in Example 4-1, which returns the correct string.
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 located at
$array[count($array)-1]
. This allows you to use
join( )
on $array
.
Also note that the code for case 2 actually also works correctly for case 1. And, the default code works (though inefficiently) for case 2; however, the transitive property doesn’t apply, so you can’t use the default code on elements of size 1.
Recipe 4.9 for turning an array into a
string; documentation on join( )
at
http://www.php.net/join, array_pop( )
at http://www.php.net/array-pop, and
reset( )
at
http://www.php.net/reset.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.