This site runs best with JavaScript enabled.

Simple PHP Pluralize

A simple function for pluralizing strings in PHP

I often find myself writing a if statement when I need to pluralize a noun in PHP. I recently wrote a simple function that did the task for me. I know there are PHP Pluralize functions out there, but they are a bit overkill for my needs. I got this idea from the way Django templates handles pluralizing. I once heard someone say it can't pluralize octopus. It can, but how often does that come up? My simple function here can also pluralize Octopus or any other word really.

Let's say I want to echo the following:

1There is 1 user.
2There are 2 users.

Here was my old way of doing things quick and dirty with no functions:

1There <?=($num_users == 1) ? 'is' : 'are';?> <?=$num_users?>
2user<?($num_users != 1) echo 's';?>.

Now, let's write a simple function to use:

1function pluralize($num, $plural = 's', $single = '') {
2 if ($num == 1) return $single; else return $plural;

Now I would write it like this:

1There <?=pluralize($num_users, 'are', 'is')?> <?=$num_users?>

OK, I don't know if saves me a whole lot of typing or not, but anyway, it makes it a bit easier in my mind.

Now, for the Octopus example:

11 Octopus has 8 legs.
27 Octopi have 56 legs.
1<?=$num?> Octop<?=pluralize($num, 'i', 'us')?> ha<?=pluralize($num, 've', 's')?>
2<?=(8 * $num)?> leg<?=pluralize(8 * $num)?>.

(I thought I'd better pluralize "legs" in case we ever have 0.125 Octopi)

Discuss on TwitterEdit post on GitHub

Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.

Join the Newsletter

Dustin Davis