Web Develop Forum: Pretty Printing: English List - Web Develop Forum

Jump to content

Sign In    Register    Help

Hello Guest!
  • You cannot start a new topic
  • You cannot reply to this topic
Page 1 of 1

  Pretty Printing: English List Rate Topic: ***-- 2 Votes

#1 User is offline   thinglie Icon

  • Advanced Member
  • PipPipPip
  • Group: Members
  • Posts: 41
  • Joined: 25-October 08
  • Gender:Male
  • Location:House

Posted 25 October 2008 - 05:36 PM

CODE
function english_list($array, $glue=", ", $lastglue=" and ", $oxfordglue=1) {
if (count($array) == 0) {
return FALSE;
} elseif (count($array) == 1) {
return $array[0];
}
$count = count($array)-1;
$last = $array[$count];
unset($array[$count]);
$str = join($glue, $array);
if ($oxfordglue) {
$str .= $glue;
}
$str .= "$glue"."$last";
return $str; }
This code generates a readable list:

CODE
english_list(array("Me", "You", "Him", "Her"));


returns "Me, You, Him, and Her".
<a href="http://www.gnu.org/" target="_blank"><img src="http://www.gnu.org/graphics/gnubanner-2.png" border="0" class="linked-sig-image" /></a>
<a href="http://www.fsf.org'" target="_blank">Free Software Foundation</a>
0

#2 User is offline   paulOr Icon

  • Member
  • PipPip
  • Group: Members
  • Posts: 20
  • Joined: 23-October 08
  • Location:Edinburgh, Scotland

Posted 02 November 2008 - 11:22 PM

very nice smile.gif
0

#3 User is offline   Salathe Icon

  • Advanced Member
  • Icon
  • Group: Moderator
  • Posts: 138
  • Joined: 15-January 09
  • Gender:Male
  • Location:Scotland

Posted 15 January 2009 - 02:10 PM

Another alternative (behaves similarly though not precisely the same) :


CODE
echo english_list(array('Peter', 'Paul', 'Mary'));

function english_list($list, $conjunction = ' and ', $glue = ', ', $serial_comma = FALSE)
{
    if (is_scalar($list))
        return (string) $list;
    
    if ( ! is_array($list) || empty($list))
        return '';
    
    $end    = array_pop($list);
    $result = implode($glue, $list);
    if (count($list))
    {
        $result .= $serial_comma ? $glue : '';
        $result .= $conjunction;
    }
    $result .= $end;
    
    return $result;
}

salathe@php.net
0

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users