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.
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.
If your intention is to show comma after each element except the last one, you can easily use $loop->last() inside your foreach.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With