Last active
January 6, 2016 09:37
-
-
Save coolamit/5207364 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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