3v4l.org

run code in 300+ PHP versions simultaneously
<?php class StringUtil{ /** * Returns the English plural of the given phrase based on the value. * * @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 $phrase, float|int|array|object $value): string{ if (empty($phrase) || is_numeric($phrase)){ return $phrase; } if (is_object($value) || is_array($value)){ $val = count($value); }else{ $val = $value; } if ($val == 1){ return $phrase; } //since the value is not singular, it is plural, so we need to come up with the english plural. $last = substr($phrase, -1); $last2 = substr($phrase, -2); $replace = false; $append = false; switch($last){ case 'x': case 'z': case 's': $append = 'es'; break; case 'y': $replace = 'ies'; break; default: switch($last2){ case 'ch': case 'sh': $append = 'es'; break; default: $append = 's'; } } if ($append) { return $phrase . $append; }else if ($replace){ return substr($phrase, 0, -1) . $replace; }else{ return $phrase; } } } $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"; }
Output for 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
kibitzes misses foxes boxes items gods funs dieties touches teaches watches tests fires

preferences:
61.36 ms | 406 KiB | 5 Q