Skip to content

Instantly share code, notes, and snippets.

@angry-dan
Created July 30, 2014 11:31
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save angry-dan/e01b8712d6538510dd9c to your computer and use it in GitHub Desktop.
Save angry-dan/e01b8712d6538510dd9c to your computer and use it in GitHub Desktop.
<?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'));
@mdahlke
Copy link

mdahlke commented May 11, 2017

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()

function nl_implode($delimiter = ', ', array $list, $conjunction = 'and'){
....
}

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.

@mp035
Copy link

mp035 commented Apr 13, 2023

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