Skip to content

Instantly share code, notes, and snippets.

@CupOfTea696
Last active July 7, 2017 11:26
Show Gist options
  • Select an option

  • Save CupOfTea696/17a5f9856063889bde9beca9ee65da05 to your computer and use it in GitHub Desktop.

Select an option

Save CupOfTea696/17a5f9856063889bde9beca9ee65da05 to your computer and use it in GitHub Desktop.
Natural Language Implode for PHP
<?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