This is one of those technical nitpick things. Check out the screenshot below of the new Yahoo Answers and see if you can spot the error.

What is the error in this screenshot from Yahoo Answers?

The title of this thread kind of gives it away. Note the “1 Answers” should actually read “1 answer” and then when there ar 2 or more it should be pluralized. Let’s build some quick and dirty pluralizing code using PHP.

<?php
function pluralize($string) {
  if(substr($string,0,1) > 1) {
     return $string . ’s’;
  }
return $string;
}
echo(pluralize(‘1 Answer’));
print ‘<br />’;
echo(pluralize(‘2 Answer’));
?>

The example above seems to work great, but there is a bug in it. What if you pass this string:

echo(pluralize(‘14 Answer’));

The answer is it will return the wrong answer (14 answer, not plural) because only the first character is being evaluated. We need to strip out the number in the beginning first instead of using substr. Here’s the corrected code.

<?php
function pluralize($string) {
  preg_match(“|^([0-9]+)|”,$string,$matched);
  if($matched[1] > 1) {
     return $string . ’s’;
  }
return $string;
}
echo(pluralize(‘1 Answer’));
print ‘<br />’;
echo(pluralize(‘14 Answer’));
print ‘<br />’;
echo(pluralize(‘144 Answer’))
?>

This will return the following:

1 Answer
14 Answers
144 Answers

If you would like to add commas just use the built-in number_format() function like this:

echo(number_format(pluralize(‘1456 Answer’))); // returns 1,456
 

Oops, that dropped the answer, didn’t it? So we need to include in the pluralize() function like this:

<?php
function pluralize($string) {
  preg_match(“|^([0-9]+)(.*)|”,$string,$matched);
  if($matched[1] > 1) {
     return number_format($matched[1]) . $matched[2] . ’s’;
  }
return $string;
}
echo(pluralize(‘1456 Answer’));
?>

Now we’ll get 1,456 Answers pluralized.

Other solutions
Here’s another way to pluralize that requires passing a number and arguments in various languages.