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')); | |
I use this all the time. Thank you.
For anyone coming here, I recently rewrote it for typescript to use client-side:
export default function naturalLanguageJoin(items: Array<string>, conjunction: string = "and"): string{
/**
* Join a string with a natural language conjunction at the end.
* https://gist.github.com/angry-dan/e01b8712d6538510dd9c
*/
// arrays are mutable and passed by reference in javascript,
// so copy the array before working on it.
const list = [...items];
const last = list.pop();
if (list.length > 0) {
return `${list.join(', ')} ${conjunction} ${last}`;
}
return last || "";
}
Credit to the original author.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First, like the function.
Second, PHP annoys me already with the way they switch arguments around for different functions. I would suggest switching the arguments to better match the implode() function since this is what it most resembles. Also, toats up to you, but I renamed it to also signify the fact that mostly it resembles implode()
Last but not least, those var_dump()'s are calling an undefined function :)
I understand if you don't change anything, but this may be beneficial for any newcomers to this snippet.