PHP Code

The following code returns the correct pluralization of a given english word based on the number provided.

/**
 * Returns the correct plural or singular form of the given word
 * @param $word String singular form of the word
 * @param $num int number of things the word is referring to
 * @return string correct form of the given word for the input number
 */
function pluralize($word, $num){
  $vowels = ["a", "e", "i", "o", "u"];
  if($num == 1){
    return $word;
  }
  if(substr($word, -1, 1) == "y" && !in_array(substr($word, -2, 1), $vowels, true)){
    return substr($word, 0, strlen($word)-1)."ies";
  }
  else if(substr($word, -1, 1) == "s"){
    return $word."es";
  }
  else{
    return $word."s";
  }
}

Leave a Reply