You can use the join()
function to combine a list of items using the same separator. But this function will join all but the last two items with a comma, and the last pair will be joined with and
, creating an easier to read list.
Ex: Item 1, Item 2 and Item 3
/**
* Join Multiple Items
* Separate last two items by 'and', remaining by commas
* Ex: item 1, item 2 and item 3
*/
function ea_join_multiple( $items ) {
if ( empty( $items ) ) {
$output = '';
} elseif ( 1 == count( $items ) ) {
$output = $items[0];
} else {
// Combine all but last partial using commas.
$output = implode( ', ', array_slice( $items, 0, -1 ) );
// Add 'and' separator.
$output .= ' and ';
// Add last partial.
$output .= end( $items );
}
return $output;
}