Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add commas to items and with "and" near the end in PHP

Tags:

loops

php

csv

I want to add a comma to every item except the last one. The last one must have "and".

Item 1, Item 2 and Item 3

But items can be from 1 +

So if one item:

Item 1

If two items:

Item 1 and Item 2

If three items:

Item 1, Item 2 and Item 3

If four items:

Item 1, Item 2, Item 3 and Item 4

etc, etc.

like image 812
SDZ Avatar asked Jan 30 '12 15:01

SDZ


People also ask

How to add comma separated values in PHP?

The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.

How do you put a comma in a foreach loop?

If your intention is to show comma after each element except the last one, you can easily use $loop->last() inside your foreach.

What does a comma do in PHP?

The comma here is used to separated arguments of the isset function. The previous explanation doesn't work with empty() for example since the empty function only takes 1 argument. TL;DR: isset($a, $b) == isset($a) && isset($b) , but empty($a, $b) is a syntax error. Save this answer.


1 Answers

Here's a variant that has an option to support the controversial Oxford Comma and takes a parameter for the conjunction (and/or). Note the extra check for two items; not even Oxford supporters use a comma in this case.

function conjoinList($items, $conjunction='and', $oxford=false) {
    $count = count($items);

    if ($count === 0){
        return '';
    } elseif ($count === 1){
        return $items[0];
    } elseif ($oxford && ($count === 2)){
        $oxford = false;
    }

    return implode(', ', array_slice($items, 0, -1)) . ($oxford? ', ': ' ') . $conjunction . ' ' . end($items);
}
like image 161
jaybrau Avatar answered Oct 05 '22 22:10

jaybrau