Display List in PHP with Commas and "And"

When you have a list of items stored in an array, PHP's built-in implode function does a decent job of quickly displaying them on the screen, but it fails to address the linguistic custom of adding an "and" before the last item in the list. Here's a quick function I wrote to solve this problem:

function commas_and($list,$comma=', ',$and=', and ') {
	if (count($list) <= 2) {
		$and = str_replace($comma,' ',$and); //no comma if there are only 2 items
		return implode($and,$list);
	} else { //if there are more than 2 items
		$string = '';
		$separator = ''; //no comma before first item
		$i = 0;
		foreach ($list as $item) {
			$string .= $separator.$item;
			if ($i == (count($list) - 1)) { $separator = $and; } //before last item
			else { $separator = $comma; } //before all other items
		return $string;

To show how it works, here are a few examples:

$animals = array('buffalo','alligator','lion','penguin');
echo commas_and($animals);

Result: buffalo, alligator, lion, and penguin

$animals = array('alligator','lion','penguin');
echo commas_and($animals);

Result: alligator, lion, and penguin

$animals = array('alligator','lion','penguin');
echo commas_and($animals,', ',' & ');

Result: alligator, lion & penguin

$animals = array('lion','penguin');
echo commas_and($animals);

Result: lion and penguin

$animals = array('lion','penguin');
echo commas_and($animals,', ',' & ');

Result: lion & penguin

$animals = array('penguin');
echo commas_and($animals);

Result: penguin

As you can see, the function handles groups of 3 or more the same. Groups of 2 lose the comma, but keep the and (a slightly modified version of it). And groups of 1 – which aren't really groups at all, are they? – are returned without any separators at all.

If you do specify $comma and $and (they're both optional), make sure to include a space after each.



This post was published on September 22nd, 2014 by Robert James Reese in PHP Before using any of the code or other content in this post, you must read and agree to our terms of use.