Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

2.10. Printing Correct Plurals

Problem

You want to correctly pluralize words based on the value of a variable. For instance, you are returning text that depends on the number of matches found by a search.

Solution

Use a conditional expression:

$number = 4;
print "Your search returned $number " . ($number == 1 ? 'hit' : 'hits') . '.';
Your search returned 4 hits.

Discussion

It’s slightly shorter to write the line as:

print "Your search returned $number hit" . ($number == 1 ? '' : 's') . '.';

However, for odd pluralizations, such as “person” versus “people,” we find it clearer to break out the entire word rather than just the letter.

Another option is to use one function for all pluralization, as shown in the pc_may_pluralize( ) function in Example 2-2.

Example 2-2. pc_may_pluralize( )

function pc_may_pluralize($singular_word, $amount_of) {

    // array of special plurals
    $plurals = array(
        'fish' => 'fish',
        'person' => 'people',
    );

    // only one
    if (1 == $amount_of) {
        return $singular_word;
    }

    // more than one, special plural
    if (isset($plurals[$singular_word])) {
        return $plurals[$singular_word];
    }

    // more than one, standard plural: add 's' to end of word
    return $singular_word . 's';
}

Here are some examples:

$number_of_fish = 1;
print "I ate $number_of_fish " . pc_may_pluralize('fish', $number_of_fish) . '.';

$number_of_people = 4; 
print 'Soylent Green is ' . pc_may_pluralize('person', $number_of_people) . '!';
I ate 1 fish.
               Soylent Green is people!

If you plan to have multiple plurals inside ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata