Skip to content

Instantly share code, notes, and snippets.

@coolamit
Last active January 6, 2016 09:37
Show Gist options
  • Save coolamit/5207364 to your computer and use it in GitHub Desktop.
Save coolamit/5207364 to your computer and use it in GitHub Desktop.
<?php
/**
* This function accepts an array and joins all values in a string separated by
* a comma except the last value which is preceeded by 'and' instead of a comma
*/
function to_sentence( $array = array() ) {
if( empty( $array ) || ! is_array( $array ) ) {
return $array;
}
switch( count( $array ) ) {
case 1:
$string = array_pop( $array );
break;
case 2:
$string = implode( ' and ', $array );
break;
default:
$last_string = array_pop( $array );
$string = implode( ', ', $array ) . ' and ' . $last_string;
break;
}
return $string;
}
//EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment