<?php
class StringUtil{
/**
* Returns the English plural of the given phrase based on the value.
* Note, there are certainly exceptions and if someone wants to white/black-list them, go ahead.
* Some exceptions that do not work with this function noted by mickmackusa:
* appendix, axis, fungus, deer, child, syllabus, louse, person, goose, bacterium
* @see first version: https://3v4l.org/VJni0
* @see https://stackoverflow.com/a/34254595/1993494 (idea from this)
* @param string $phrase The phrase to determine the plural form
* @param float|int|array|object $value The value to determine whether the phrase should be plural or not
* @return string The English plural form of the phrase based on the value
*/
public static function pluralEnglish(string $singularPhrase, float|int|array|object $value): string{
if ($value === 1){
return $singularPhrase;
}
if (is_countable($value)){
if (count($value) === 1){
return $singularPhrase;
}
}else if (is_object($value)){
//object that does not implement Countable
return $singularPhrase;
}
//If the string doesn't even end with a letter, just return the phrase.
if (!preg_match('/[a-zA-Z]$/', $singularPhrase)){
return $singularPhrase;
}
if (str_ends_with($singularPhrase, 'y')){
return substr($singularPhrase, 0, -1).'ies';
}
//In English, words that end with these characters, you add "es" to make them plural.
$es_append = ['x','z','s','ch','sh'];
foreach($es_append as $end){
if (str_ends_with($singularPhrase, $end)){
return $singularPhrase.'es';
}
}
//It didn't fit any of the above criteria, so just add "s"
return $singularPhrase.'s';
}
}
$ary = [
'kibitz',
'miss',
'fox',
'box',
'item',
'god',
'fun',
'diety',
'touch',
'teach',
'watch',
'test',
'fire',
];
$count = 0;
foreach($ary as $phrase){
echo StringUtil::pluralEnglish($phrase, $count)."\n";
}