Using foreach loop to output grammatically correct list

Written by | March 4, 2011 | Posted in Process

While building out this site, I ran into the issue of how to output an array in a grammatically correct manner. For example, I needed to generate the following sentence based on items stored in array:

“My favorite foods are cheese, apples, bacon, popcorn and pizza.”

There are two issues at stake here. One is that last item must have the word “and” before it and the other is that the second-to-last item must not have a comma after it. (Let’s not have an Oxford Comma debate here for the sake of simplicity!) The following code will allow for grammatically correct output of an array of 1 or more items.

$last_item = array_pop($items);
foreach ($items as $num => $item) {
if (isset($types[$num+1])) {
echo $item . ', ';
} else {
echo $item . ' and ';
}
}
echo $last_item;

Let’s break it down. The first line will pop the last item off the array into a new variable. Guess what this does for us? Yep, it makes your second-to-last item the new last item in your array. The foreach loop iterates through the array $types and separates the array key and value into their own unique variables ($num and $item, respectively). Then, the if statement checks to see if there is an item with a key beyond our current item’s key. If so, it outputs the item followed by a comma and space. If not, it outputs the item followed by only a space. Finally, the last item is outputted following an “and” and a space!