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?
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With