I was just reading David Walsh’s post about Possessives. It was a very clever use of PHP. I remembered a helper method I wrote last year that was somewhat similar in use, another form of coding English. It was Pluralization.
At first I just added s if the first argument was not 1 and that won’t always work. For instance, while blog will pluralize with just an s but box will not. Is there a solution to this horrible problem? Yes.
The solution is a three argument function, although exhausting, it does get the job done. So I provide these functions in Java, the original language, javascript and PHP.
Java
This method accepts a double and two strings. The first argument is a double for a technical reason. Do you say, “I have .57 apples?” or “I have .57 of an apple?” My conclusion was that decimals were plural. It sounds right. Is it linguistically correct? Somebody should tell me.
public static String pluralize(double howMany, String singular, String plural) { return ( howMany == 1.00 ? singular : plural ); }
Javascript
function pluralize(howMany, singular, plural) { return ( howMany == 1.00 ? singular : plural ); }
PHP
function pluralize($howMany,$ singular, $plural) { return ( $howMany == 1.00 ? $singular : $plural ); }
The code for this method is based off of the Java version and because they all have similar syntax, they all look the same. Using something like this won’t be useful in a internationalization-localization context but it can help for tiny projects.
A little example and that should do it.
$itemsInCart = 1; echo( "There " . pluralize($itemsInCart, "is one item", "are items" ));
Great work Ryan! I like what you’ve done!