Create a string from a list of array values merged with comma and "and" as the last
PHP
/**
* Create a string from a list of array values merged with comma
* and "and" as the last.
*
* @param $array
* @return string
*/
function implode_with_comma_and_and($array) {
if (empty($array)) {
return '';
}
// Prepare implode.
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge([$first], $last), 'strlen');
return implode(' and ', $both);
}
JavaScript
/**
* Create a string from a list of array values merged with comma
* and "and" as the last.
*
* @param array
* @returns string
*/
function implodeWithCommaAndAnd(array) {
if (array.length === 0) {
return '';
}
return [array.slice(0, -1).join(', '), array.slice(-1)[0]].join(array.length < 2 ? '' : ' and ');
}