I wrote the below method to list out the elements of an array, as well as adding the Oxford comma to the list if desired. However, my for-loop looks, perhaps, a little convoluted. Is there a better way to handle clearly both the Oxford comma and the ability to add a conjunction?
function listOut($array = array(), $oxford = false, $conjunction = 'and') {
$count = is_array($array) ? count($array) : 0;
switch($count) {
case 0: // Either not an array or an empty array
return '';
case 1: // Only one element in the array, return it
return $array[0];
case 2: // Two elements; join them together with the conjunction
return "{$array[0]} {$conjunction} {$array[1]}";
default: // At least two elements, join with commas and conjunction
$s = ", ";
$t = "";
for($i = 0; $i < $count; $i++) {
// Add a conjunction if it's the last element in the array
if($i + 1 === $count) {
$s = $oxford ? $s . "$conjunction " : " $conjunction ";
}
// Only prepend comma if not the first element
if($i > 0) {
$t .= $s;
}
// Add the element to the return string
$t .= $array[$i];
}
return $t;
}
}
$array1 = array('orange');
$array2 = array('white', 'gold');
$array3 = array('black', 'white', 'purple');
echo listOut($array1); // orange
echo listOut($array2); // white and gold
echo listOut($array3); // black, white and purple
echo listOut($array1, true); // orange
echo listOut($array2, true); // white and gold
echo listOut($array3, true); // black, white, and purple