Join Multiple Items

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

<?php
/**
* 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;
}
view raw helper-functions.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk