RSS

Newsletter

The CodeKarate Newsletter is the best way for technical ninjas to keep their swords sharpened. Don't worry, we won't flood your inbox and your email address will always remain private.
Back to Top

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

1
Rochii Seara (not verified)

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

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <blockquote> <img>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <php>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <python>, <ruby>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.