Created
July 30, 2014 11:31
-
-
Save angry-dan/e01b8712d6538510dd9c to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Join a string with a natural language conjunction at the end. | |
*/ | |
function natural_language_join(array $list, $conjunction = 'and') { | |
$last = array_pop($list); | |
if ($list) { | |
return implode(', ', $list) . ' ' . $conjunction . ' ' . $last; | |
} | |
return $last; | |
} | |
// null | |
var_dump(natural_join(array())); | |
// string 'one' | |
var_dump(natural_join(array('one'))); | |
// string 'one and two' | |
var_dump(natural_join(array('one', 'two'))); | |
// string 'one, two and three' | |
var_dump(natural_join(array('one', 'two', 'three'))); | |
// string 'one, two, three or four' | |
var_dump(natural_join(array('one', 'two', 'three', 'four'), 'or')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this all the time. Thank you.
For anyone coming here, I recently rewrote it for typescript to use client-side:
Credit to the original author.