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

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

Barbara Streisand
Release: 2024-11-27 18:42:11
Original
288 people have browsed it

How Can I Implode an Array with Commas and

Imploding an Array with Commas, Adding "and" Before the Final Item

Imploding an array into a string can be straightforward, but adding an "and" before the last item requires a bit more finesse. Consider an array of beverages:

[
    "coke",
    "sprite",
    "fanta"
]
Copy after login

Imploding this array with a comma returns:

coke, sprite, fanta
Copy after login

However, we want to modify it to:

coke, sprite and fanta
Copy after login

Here's how you can achieve this using a combination of array slicing, merging, filtering, and joining:

$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 method efficiently handles arrays of all sizes, including cases with zero, one, or two elements, without the need for additional conditional statements. The versatility of this approach allows it to be collapsed into a single line:

echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
Copy after login

This long-line solution ensures proper handling of all scenarios, from empty arrays to large lists of items.

The above is the detailed content of How Can I Implode an Array with Commas and \'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