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
Release: 2024-12-02 01:04:10
Original
572 people have browsed it

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
Copy after login

should become:

coke, sprite and fanta
Copy after login

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'));
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template