Recipe 4.9. Printing an Array with Commas


4.9.1. 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.

4.9.2. Solution

Use the pc_array_to_comma_string( ) function shown in Example 4-1, which returns the correct string.

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";     } }

4.9.3. 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 located at $array[count($array)-1]. This allows you to use join( ) on $array.

Also note that the code for case 2 actually works correctly for case 1, too. 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.

4.9.4. See Also

Recipe 4.8 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.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net