Skip to content

Instantly share code, notes, and snippets.

@fdorantesm
Created February 9, 2018 17:10
Show Gist options
  • Save fdorantesm/642582d184fe38ac4ca250f72c9288c8 to your computer and use it in GitHub Desktop.
Save fdorantesm/642582d184fe38ac4ca250f72c9288c8 to your computer and use it in GitHub Desktop.
Human implode
<?php
function human_implode($glue = ",", $last = "y", $elements = array(), $filter = null){
if ($filter) {
$elements = array_map($filter, $elements);
}
$str = implode("{$glue} ", $elements);
if (count($elements) == 2) {
return str_replace("{$glue} ", " {$last} ", $str);
}
return preg_replace("/[{$glue}](?!.*[{$glue}])/", " {$last}", $str);
}
<?php
require 'helpers.php';
print_r("<pre>");
print_r(human_implode(",", "y", ["Hugo", "Paco", "Luis"]));
print_r("<br>");
print_r(human_implode(",", "y", ["limón sin semilla", "melón chino", "jitomate saladette"], "ucfirst"));
print_r("<br>");
print_r(human_implode(",", "y", ["chalequito matón", "pantaloncito trucutrú"], "ucwords"));
print_r("<br>");
print_r(human_implode(",", "o", ["Guillermo Ochoa", "José de Jesús Corona", "Alfredo Talavera"], "mb_strtoupper"));
print_r("</pre>");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment