Last active
July 7, 2017 11:26
-
-
Save CupOfTea696/17a5f9856063889bde9beca9ee65da05 to your computer and use it in GitHub Desktop.
Natural Language Implode for PHP
This file contains hidden or 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 | |
| if (! function_exists('nl_implode')) { | |
| function nl_implode(array $list, $conjunction = 'and', $oxford_comma = true) { | |
| $last = array_pop($list); | |
| if ($list) { | |
| return implode(', ', $list) . ($oxford_comma ? ',' : '') . ' ' . $conjunction . ' ' . $last; | |
| } | |
| return (string) $last; | |
| } | |
| } | |
| /** | |
| * Examples | |
| */ | |
| var_dump(nl_implode([])); | |
| // string '' | |
| var_dump(nl_implode(['one'])); | |
| // string 'one' | |
| var_dump(nl_implode(['one', 'two'])); | |
| // string 'one, and two' | |
| var_dump(nl_implode(['one', 'two', 'three'])); | |
| // string 'one, two, and three' | |
| var_dump(nl_implode(['one', 'two', 'three', 'four'], 'or')); | |
| // string 'one, two, three, or four' | |
| var_dump(nl_implode(['one', 'two', 'three', 'four'], 'and', false)); | |
| // string 'one, two, three and four' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment