Add commas to items and with “and” near the end in PHP

后端 未结 6 572
名媛妹妹
名媛妹妹 2021-01-12 03:08

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 on

6条回答
  •  有刺的猬
    2021-01-12 03:45

    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);
    }
    

提交回复
热议问题