Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Last active September 26, 2015 01:58
Show Gist options
  • Save chrisbloom7/1021214 to your computer and use it in GitHub Desktop.
Save chrisbloom7/1021214 to your computer and use it in GitHub Desktop.
Given an array of 0 or more values, pretty_join() will concatenate all of the values together using a common delimiter (a comma by default) except for the last two values which will be joined by the final separator (an ampersand by default).
<?php
function pretty_join($array, $intermediate_separator = ', ', $final_separator = ' & ')
{
if (!is_array($array)) return null;
switch (sizeof($array))
{
case 0: return null; break;
case 1: return reset($array); break;
case 2: return implode($final_separator, $array); break;
default:
$end = array_pop($array);
// This second call prevents the last two elements from being reversed
$end = array_pop($array) . $intermediate_separator . $final_separator . $end;
array_push($array, $end);
return implode($intermediate_separator, $array);
}
}
?>
<?php
//pretty_join with 0 elements
echo pretty_join(array());
// =>
//pretty_join with 1 elements
echo pretty_join(array('Big Tires'));
// => Big Tires
//pretty_join with 2 elements
echo pretty_join(array('Big Tires', 'Pretty Houses'));
// => Big Tires & Pretty Houses
//pretty_join with 3 elements
echo pretty_join(array('Big Tires', 'Pretty Houses', 'Fat Wives'));
// => Big Tires, Pretty Houses, & Fat Wives
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment