
Plurals With PHP
- by Gareth Williams
Take a stand for good grammar on your website and get your plurals right.
Tackling the issue of plurals in dynamic web pages is often bypassed with ugly workarounds. There's the forced plural, where the plural of the word is always displayed regardless of the quantity. This reads poorly and is quite simply incorrect. Take a look at this example:
<?php echo "You have logged in $num times"; ?>
Outputs:
You have logged in 1 times.
The programmer has opted to display the word "times" regardless of whether it is grammatically correct or not. It smacks of laziness.
The second offender is the figure-it-out-yourself plural, where, in an attempt to cater for all occasions, the programmer has used both the singular and the plural of the word, as in this example.
<?php echo "There is/are $num item(s) in your basket"; ?>
Outputs:
There is/are 1 item(s) in your basket
There is/are 5 item(s) in your basket
This method is downright ugly.
Here's a remarkably simple, but elegant, solution. It takes only a fraction longer to make an accessible string of text using the 'plural' function, as demonstrated here for use on a bulletin board:
<?php echo "You have made $num ", plural( $num, 'post', 'posts' ); ?>
Outputs:
You have made 0 posts
You have made 1 post
You have made 5 posts
Here is the code for the plural function. Please feel free to include it in your code toolbox:
<?php
/*---- plural ----
This function takes as its first parameter an integer. If the integer is 1, the function returns the second parameter (the singular), otherwise it returns the third parameter (the plural).
----------------*/
function plural( $quantity, $singular, $plural )
{
if( intval( $quantity ) == 1 )
return $singular;
return $plural;
}
?>