Home >Backend Development >PHP Tutorial >How Can I Implode an Array with Commas, Inserting \'and\' Before the Last Item?

How Can I Implode an Array with Commas, Inserting \'and\' Before the Last Item?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 01:04:10657browse

How Can I Implode an Array with Commas, Inserting

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn