PHP Numbers
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') . '.';
This prints:
Your search returned 4 hits.
Discussion
Example may_pluralize()
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:
$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, youreturn 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 language specific logic is reasonable. If your application needs to produce output in many languages, then a more comprehensive approach is necessary.
No comments:
Post a Comment