Created
August 13, 2020 06:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check out this gist for a simpler version of the function that doesn't support custom string wrapping.