Created
August 13, 2020 06:41
-
-
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.
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) { | |
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 more advanced version of the function that supports custom string wrapping.