Skip to content

Instantly share code, notes, and snippets.

@newbold
Created August 13, 2020 06:42
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/b7094babf30500354987fbb5ddf412d7 to your computer and use it in GitHub Desktop.
Save newbold/b7094babf30500354987fbb5ddf412d7 to your computer and use it in GitHub Desktop.
This function turns an array into a nice list, with list items wrapped in custom strings, separated with commas, with "and" before the final item.
<?php
function nice_list($items, $wrapper = false) {
if($wrapper) {
$wrapper = str_split($wrapper, strlen($wrapper) / 2);
foreach($items as &$item) {
$item = $wrapper[0].$item.$wrapper[1];
}
}
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 simpler version of the function that doesn't support custom string wrapping.

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