Pluralize Intelligently with PHP

Album Cover: Wincing the Night Away

"It's like I'm perched on the handlebars of a blind man's bike."
The Shins / Spilt Needles

Posted on June 03, 2006 1:53 PM in Web Development
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

If you've ever created a blog or other site that reports article views or comments, you've probably run into the problem of intelligently handling the pluralization of words. For example, if there has been only one comment on a particular article or blog entry, you'll want to report "1 comment" and not "1 comments," since the former is obviously more intelligent and appropriate. This problem is an easy one to solve, but here's a function you can use if you don't feel like reinventing the wheel:

// function for pluralizing a word intelligently
function pluraleyes($num, $word)
{
 return ($num == 1) ? $word : $word . 's';
}

Then, to utilize the function, simply call it like this:

Article viewed <? echo $views . ' ' . pluraleyes($views, 'time'); ?>.

Easy, right?

Comments

Mike on June 05, 2006 at 3:08 PM:

It's a bit picky of me, but you might want to expand your function a bit to include the singular and the plural form of the word. Tacking a "s" onto the end of the word doesn't always work, thanks to all the wonderful "rules" we have in the English language. Having something like "1 person dugg this article" and "14 people dugg this article" makes things read a little easier.

Permalink

Bernie Zimmermann on June 05, 2006 at 7:22 PM:

Good point, Mike. The function isn't very robust at all, and I actually meant to point that out. There are other rules such as "3 passers by" or "9 octopii" that need to be considered as well (although my function might actually accidentally handle the former). Luckily I'm not tracking octopii visits on any of my sites ;)

If anyone creates a more robust version of the function, please either share or post a link here!

Permalink

Logan Koester on December 17, 2007 at 10:51 AM:

Good enough for what I'm doing at the moment. Thank you!

Permalink

Nick on September 08, 2010 at 8:00 AM:
Click Here on February 12, 2017 at 11:33 PM:

A lot of users have thousands likes for their posts.

Permalink

free xbox live on February 14, 2017 at 5:52 AM:

This site is very powerful for me with the xbox app create your own gaming communities with clubs on xbox live.

Permalink

http://www.theoriginalhcgdrops.com/ on March 10, 2018 at 9:38 AM:

Excellent website you have here, so much cool information!..

Permalink

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.

Name:

Email Address:

Website:

Comments:

Check this box if you hate spam.