How to Pluralize Words with PHP

Josh Sherman
1 min read
Software Development PHP

There’s a good chance you’ve seen it before (and possibly authored it), it looks something like this “You have 1 new messages” or “There are 10 user(s) logged in”. What you end up with is something that’s either incorrect or something like looks a bit amateurish. To fix this, we just need a bit of logic of course ;) All you need to do is check how many we have and output the word accordingly:

echo 'You have ' . $new . ' new ' . ($new == 1 ? 'message' : 'messages');
// a slightly shorter version:
echo 'You have ' . $new . ' new message' . ($new == 1 ? '' : 's');

This gets cumbersome so most of us resort to writing our own helper function that accomplishes this. Fortunately, PHP actually has a function that can accomplish this:

echo 'There ' . ngettext('is', 'are', $online) . ' ' . $online . ' ' . ngettext('user', 'users', $online) . ' logged in';

ngettext() takes 3 arguments, the singular version of a word, the plural version and the integer value to use to determine which to use.

Both of these are very simple examples on how to pluralize a word and can easily be used to handle complex plural words like mice or octopi. If you’re looking for more complex solution where you can simply pass in a word and number and get the plural back, check out Paul Osman’s PHP Pluralize Method.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles