# Recipe 2.11. Printing Correct Plurals

#### 2.11.1. 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.

#### 2.11.2. Solution

Use a conditional expression:

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

#### 2.11.3. Discussion

The line is slightly shorter when written 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-5.

##### pc_may_pluralize( )

 ` '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 your code, using a function such as pc_may_pluralize( ) increases readability. To use the function, pass pc_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.

PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon