Human join / implode helper

Did you notice that when humans list items, they use a different glue for the last item?
“Who was there?” “Tom, Bob and Jane.”

Here’s a Nette helper that does the same.

  1.  
  2. public function humanJoin($pieces, $glue = ‘, ‘, $lastGlue = ‘ and ‘)
  3. {
  4.   if (empty($pieces)) {
  5.     return null;
  6.   }
  7.  
  8.   if (count($pieces) == 1) {
  9.     return array_shift($pieces);
  10.   }
  11.  
  12.   $lastItem = array_pop($pieces);
  13.   return join($glue, $pieces) . $lastGlue . $lastItem;
  14. }
  15.  

Use as {$friends|humanJoin} or {$aliens|humanJoin:’, ‘:’ nor ‘}.

Leave a Reply