What is the best way to prepend a conjunction to the end of an imploded array in PHP?
Danronmoon’s Questions:
Let’s say I have an array.
$shopping_list = array('eggs', 'butter', 'milk', 'cereal');
What is the easiest and/or most clever way to display this as a comma-delimited list and prepend a word (conjunction, preposition, etc.) to the last value? Desired results include:
'eggs, butter, milk, and cereal'
'eggs, butter, milk, or cereal'
'eggs, butter, milk, with cereal'
'eggs, butter, milk, in cereal'
// etc.
The array will be of variable length, may be associative, and preferably it shouldn’t be modified. It needn’t be imploded either; I figure this is just the standard way of doing things like this. Array dereferencing is fine too, but something PHP 5.3-compatible would be great.
I’m thinking something along the lines of
$extra_word = 'and';
implode(', ', array_slice($shopping_list, 0, count($shopping_list) - 1))
. ', ' . $extra_word . ' '
. implode(',', array_slice($shopping_list, count($shopping_list) - 1));
But that’s a doozy. Loops are cleaner and slightly less inept:
$i = 0;
$output = '';
foreach ($shopping_list as $item) {
$i += 1;
if ($i > 1) {
$output .= ', ';
if ($i === count($shopping_list)) {
$output .= $extra_word . ' ';
}
}
$output .= $item;
}
Both of these ways seem roundabout. Is there a better way out there that comes to mind?
This is cleaner too.
$pop = array_pop($shopping_list);
echo implode(", ", $shopping_list)." and $pop.";