Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pluralize in PHP [duplicate]

There are a lot of questions explaining how to echo a singular or plural variable, but none answer my question as to how one sets a variable to contain said singular or plural value.

I would have thought it would work as follows:

$bottom="You have favourited <strong>$count</strong> " . $count == 1 ? 'user':'users';

This however does not work.

Can someone advise how I achieve the above?

like image 833
Thomas Clowes Avatar asked Oct 08 '12 17:10

Thomas Clowes


2 Answers

You can try this function I wrote:

/**
 * Pluralizes a word if quantity is not one.
 *
 * @param int $quantity Number of items
 * @param string $singular Singular form of word
 * @param string $plural Plural form of word; function will attempt to deduce plural form from singular if not provided
 * @return string Pluralized word if quantity is not one, otherwise singular
 */
public static function pluralize($quantity, $singular, $plural=null) {
    if($quantity==1 || !strlen($singular)) return $singular;
    if($plural!==null) return $plural;

    $last_letter = strtolower($singular[strlen($singular)-1]);
    switch($last_letter) {
        case 'y':
            return substr($singular,0,-1).'ies';
        case 's':
            return $singular.'es';
        default:
            return $singular.'s';
    }
}

Usage:

pluralize(4, 'cat'); // cats
pluralize(3, 'kitty'); // kitties
pluralize(2, 'octopus', 'octopii'); // octopii
pluralize(1, 'mouse', 'mice'); // mouse

There's obviously a lot of exceptional words that this function will not pluralize correctly, but that's what the $plural argument is for :-)

Take a look at Wikipedia to see just how complicated pluralizing is!

like image 165
mpen Avatar answered Oct 17 '22 05:10

mpen


The best way IMO is to have an array of all your pluralization rules for each language, i.e. array('man'=>'men', 'woman'=>'women'); and write a pluralize() function for each singular word.

You may want to take a look at the CakePHP inflector for some inspiration.

https://github.com/cakephp/cakephp/blob/master/src/Utility/Inflector.php

like image 24
Jesse Kochis Avatar answered Oct 17 '22 06:10

Jesse Kochis