Serial commas and PHP

I love serial commas (putting a comma before “and” in a list. I.e. one, two, and three). People call them old-fashioned and clunky, but they really help with clarity (see this article for an example).

The thing I don’t like about serial commas is trying to automate their formatting. I can’t find examples anywhere, so here’s my PHP code to do it. The way I use it is a while() loop after querying a database, but it will work with any loop (i.e. a foreach’d array). $num_authors is the total number of records. $count_authors is set to 1 before the loop.

The code

Update: Charismatic Programmer posted a much better way to do this in the comments section. This is their method:

function serial_comma($array)
{
     $size = sizeof($array);
     switch($size)
     {
          case 0:
          case 1:
               return reset($array);
          case 2:
               return join(' and ', $array);
          default:
               return join(', ', array_slice($array, 0, $size – 1)).', and '.$array[$size - 1];
     }
}

Example:

$array = array('Anthony Bourdain', 'Mario Batali', 'Thomas Keller');
echo serial_comma($array);

Produces:

Anthony Bourdain, Mario Batali, and Thomas Keller

The old code

if ($num_authors == 1)
{
	echo $author;
}
else
{
	if ($num_authors > $count_authors)
	{
		if (($count_authors + 1) == $num_authors)
		{
			if ($num_authors == 2)
			{
				echo "$author and ";
			}
			else
			{
				echo "$author, and ";
			}
		}
		else
		{
			echo "$author, ";
		}
	}
	elseif ($num_authors == $count_authors)
	{
		echo $author;
	}
      	else
	{
		// error message
	}
	$count_authors++;
}

« - »

Comments

  1. CHARISMATIC PROGRAMMER | September 21st, 2011 | 7:53 am

    Try this- it will work for any array of strings

    function serial_comma($array) {
    $size = sizeof($array);
    switch($size) {
    case 0:
    case 1:
    return reset($array);
    case 2:
    return join(‘ and ‘, $array);
    default:
    return join(‘, ‘, array_slice($array, 0, $size – 1)).’, and ‘.$array[$size - 1];
    }
    }

  2. Matthew | September 28th, 2011 | 6:21 pm

    Thanks Charismatic Programmer! That is an insanely better way to do this

Post a comment