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(mb_substr($word, -1, 1) == "y" && !in_array(mb_substr($word, -2, 1), $vowels, true)){
        return mb_substr($word, 0, mb_strlen($word) - 1) . "ies";
    }
    else if(mb_substr($word, -1, 1) == "s" || mb_substr($word, -1, 1) == "o"){
        return $word . "es";
    }
    else{
        return $word . "s";
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.