Implode an Array with Commas, Adding "And" Before the Last Item
Question:
You have an array of items and want to convert it into a string, but with "and" added before the last item instead of a comma. For example:
1 => coke, 2 => sprite, 3 => fanta
should become:
coke, sprite and fanta
Answer:
One way to achieve this is using the following code:
echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
Or, for increased verbosity:
$last = array_slice($array, -1); $first = join(', ', array_slice($array, 0, -1)); $both = array_filter(array_merge(array($first), $last), 'strlen'); echo join(' and ', $both);
This approach handles all cases, including arrays with no, one, or two items, without the need for additional if-else statements.
The above is the detailed content of How Can I Implode an Array with Commas, Inserting \'and\' Before the Last Item?. For more information, please follow other related articles on the PHP Chinese website!