Last active
May 14, 2020 14:33
-
-
Save aphoe/9c8051b830ff49d3a51ca8db67b1ae48 to your computer and use it in GitHub Desktop.
PHP function to 'implode' array into a sentence, using 'and' before the last item
This file contains 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 | |
if(!function_exists('implodeAnd')){ | |
/** | |
* Implode array into asentence | |
* @param array $haystack | |
* @param string $glue | |
* @param string $and | |
* @return string | |
*/ | |
function implodeAnd(array $haystack, string $glue=', ', string $and = ' and '): string | |
{ | |
$str = ''; | |
$len = count($haystack); | |
//Singular/empty array | |
if(empty($haystack)){ | |
return ''; | |
}elseif ($len< 2){ | |
return $haystack[0]; | |
} | |
//Process | |
for($i=0; $i<$len; $i++){ | |
if($i === $len - 1){ | |
$str .= $haystack[$i]; | |
}else if($i === $len -2){ | |
$str .= $haystack[$i] . $and; | |
}else{ | |
$str .= $haystack[$i] . $glue; | |
} | |
} | |
return $str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Will give you
apple, mango, orange and banana