Plurals... Aren't they fun?


Can anybody really count the times they needed to have a dynamic number of items and the dreaded number 1 comes up… So your webpage looks like either:

You have 1 apples
– or even better –
You have 234 apple

So us programmers do this

[php]echo "You have ".($apples == 1 ? ‘apple’ : ‘apples’);[/php]

Sure this is rather simple to do, and it really doesn’t affect the code that much, so what’s the problem? Well let me tell you what the problem is your code starts to look like this if you have advanced or other ternary operators:

[php]echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? ‘behind’ : ‘above average’) : ($score < 50 ? ‘behind’ : ‘above average’));[/php]

So let’s simplify this, I created a function that will handle the pluralization of words to your choice:

[php]function pluralize($quantity, $singular, $plural) {
if ($quantity == 1 || !strlen($singular)) return $singular;
if ($plural !== null) return $plural;

Now you can simply do:

[php]for ($qty = 0; $qty <= 25; $qty++) {
echo “You have “.pluralize($qty, ‘apple’, ‘apples’).”