Skip to content

Instantly share code, notes, and snippets.

@newbold
Created August 13, 2020 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newbold/15d9e6b223eb468309323a460229a867 to your computer and use it in GitHub Desktop.
Save newbold/15d9e6b223eb468309323a460229a867 to your computer and use it in GitHub Desktop.
This function turns an array into a nice list, separated with commas, with "and" before the final item.
<?php
function nice_list($items) {
if(count($items) == 1) return $items[0];
if(count($items) == 2) return $items[0].' and '.$items[1];
$last = array_pop($items);
array_push($items, 'and '.$last);
return implode(', ', $items);
}
$items[] = 'pebble';
$items[] = 'bean';
$items[] = 'peanut';
$items[] = 'marble';
$items[] = 'paperclip';
echo nice_list($items); // pebble, bean, peanut, marble, and paperclip
@newbold
Copy link
Author

newbold commented Aug 13, 2020

Check out this gist for a more advanced version of the function that supports custom string wrapping.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment