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.
Use a conditional expression:
1 2 |
$number = 4; print "Your search returned $number " . ($number == 1 ? 'hit' : 'hits') . '.'; |
This prints:
1 |
Your search returned 4 hits. |
Another option is to use one function for all pluralization, as shown in the may_pluralize() function in
Example 2-2. may_pluralize()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function 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:
1 2 3 4 5 6 7 |
$number_of_fish = 1; // $out1 is "I ate 1 fish." $out1 = "I ate $number_of_fish " . may_pluralize('fish', $number_of_fish) . '.'; $number_of_people = 4; // $out2 is "Soylent Green is people!" $out2 = 'Soylent Green is ' . may_pluralize('person', $number_of_people) . '!'; |
If you plan to have multiple plurals inside your code, using a function such as may_pluralize() increases readability.
To use the function, pass may_pluralize() the singular form of the word as the first argument and the amount as the second.
Inside the function, there’s a large array, $plurals, that holds all the special cases. If the $amount is 1, you return the original word.
If it’s greater, you return the special pluralized word, if it exists. As a default, just add an s to the end of the word.
As written, may_pluralize() encapsulates pluralization rules for American English. Obviously, the rules are different for other languages.
If your application only needs to produce output in one language, then a function like may_pluralize() with languagespecific logic is reasonable.
If your application needs to produce output in many languages, then a more comprehensive approach is necessary.