A modular approach for pluralizing nouns

I think that we all ran into a problem before the application reports that there is a “1 minute” or something like that. I think this observation indicates that many programmers ignore this problem.

In my projects, I usually did something in this direction to take into account pluralizing nouns:

$Count = count($Items); $Noun = 'minute'; if ($Count != 1) { $Noun .= 's'; } echo sprintf('There are %u %s remaining.', $Count, $Noun); 

I have a couple of questions with this approach:

  • It places a burden on the programmer to perform this pluralization check every time a line is needed, so the code can never be reused.
  • It uselessly inflates application code and prohibits readability.
  • This is not common. The example worked because “minutes” is the plural of “minute”. What about "sheep", "bulls" or "mushrooms"?

Does anyone have any ideas for a universal, modular approach to solving this problem? I am fine with the fact that there is more than one answer.

+4
source share
3 answers

Usually a function is implemented that takes a number and all singular and plural adjectives.

So a call request can be

 echo 'There are ' $count . ' ' . pluralize($count, array('minute', 'minutes')) . ' remaining'; 

If you decide to translate your application into many languages, this link will help to correctly distribute the multiplicity: http://translate.sourceforge.net/wiki/l10n/pluralforms

ps: the proposition made by me will work perfectly with any languages ​​if you pass an additional third parameter language , which will indicate which pluralization formula to use.

+3
source

I think using a generic approach will overshoot performance versus the usefulness of this little code. To achieve a common approach, you should use a dictator or something similar that really is not needed compared to the benefits. Perhaps a simpler line like this is the right compromise between efficiency and utility.

 $Count = count($Items); $Noun = 'minute'; echo sprintf('There are %u %s(s) remaining.', $Count, $Noun); 
+2
source

One easy way to handle this is to create a function that takes three arguments: a number, a singular spelling of a word, and multiple spelling of a word. The function returns either an exclusive or pluralized version of the word, depending on the value. It still puts a burden on the programmer, but it is cleaner than you show here.

+1
source

All Articles