Array to String With Commas And Closing And

Last modified: 
Friday, March 27th, 2015
Topics: 
PHPArrays

Given an array of three or more values like [foo, bar, baz], implode them into string of the form, "foo, bar, and baz."

function array2StringWithCommas($array, $oxford=True) {
  $last = array_pop($array);
  $second2Last = array_pop($array);
  if ($oxford) {
    $last = $second2Last . ', and ' . $last;
  }
  else {
    $last = $second2Last . ' and ' . $last; 
  }
  array_push($array, $last);
  return implode(', ', $array);
}

Useage

$arr = array('Foo', 'Bar', 'apple'=>'Baz');
print array2StringWithCommas($arr);

Returns:

Foo, Bar, and Baz
$arr = array('Foo', 'Bar', 'apple'=>'Baz');
print array2StringWithCommas($arr, False);

Returns:

Foo, Bar and Baz


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.