Pluralizing words in Drupal with format_plural
I frequently run into a common situation that I am sure many Drupal developers run into. For example, lets say I am printing out some text that has a number followed by a noun. An example might be 10 products. However, often times the number that you print out will be a variable. In this case everything is fine until you run into this situation 1 products. While this is more of an annoyance than anything, in the spirit of being grammatically correct, what it should say is 1 product.
So how do we fix this. Well, if you were building something in custom PHP you would be reduced to writing your own simple replacement function (which really isn't too difficult, but is a hassle nonetheless). In Drupal we are lucky enough to have a function built into Drupal core to do this for us. The function is format_plural.
The documentation on Drupal.org sums it up pretty well but the most basic example (this will work for Drupal 6 or Drupal 7) goes something like this:
format_plural($cnt, 'product', 'products');
This will print out the word product if the $cnt variable is 1 and products if the count variable is anything else.
Simple I know... but its something that can save you a lot of time and is a function that almost all Drupal developers should know about.
Have any other helpful Drupal functions that you know about and use often? Let me know in the comments below.



Discussions
I am a developer too and i
I am a developer too and i have to admit that i run into the same problem a several times and i didn't know what to do! Thanks for providing us a solution! good article!
Post new comment