Skip to content

Instantly share code, notes, and snippets.

@aphoe
Last active May 14, 2020 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aphoe/9c8051b830ff49d3a51ca8db67b1ae48 to your computer and use it in GitHub Desktop.
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
<?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;
}
}
@aphoe
Copy link
Author

aphoe commented May 14, 2020

Example

<?php
 $array = ['apple', 'mango', 'orange', 'banana'];
implodeAnd($array);

Will give you
apple, mango, orange and banana

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment