Auto Pluralize

I created a little helper for auto-pluralizing a word using the Inflection class that comes with CakePHP. All I do is pass it the word and the count. The result will be something like, "1 member" or "2 members".


class PluralHelper extends Helper {

  //$s = the string
  //$c = the count
  function ize($s, $c)
  {
    if($c == 0 || $c > 1)
    {
      $inflect = new Inflector();
      return $c . ' ' . $inflect->pluralize($s);
    }else{
      return $c . ' ' . $s;
    }
  }
}

Using the Plural helper is really easy. First, be sure to add it to your controller:

var $helpers = array('Html','Plural');

After that, in your view, call it like this:

echo $plural->ize('member',2)
Published July 14, 2006 · Updated July 14, 2006
Categorized as CakePHP
Short URL: https://snook.ca/s/686

Conversation

3 Comments · RSS feed
Jesse Morrow said on April 01, 2007

Great Helper,

I'd suggest using:

if($c != 1) {...}

instead of your current condition. That way you properly cover all the decimal cases too such as 0.1 or 1.5, etc.

If you give it some thought: the only time you don't use the plural with a numer before the word is for 1!

montreal canadiens tickets said on February 23, 2011

Hey,

This is a inquiry for the webmaster/admin here at www.snook.ca.

Can I use part of the information from your blog post above if I provide a link back to your website?

Thanks,
Harry

montreal canadiens tickets said on March 02, 2011

Hello there,

I have a message for the webmaster/admin here at www.snook.ca.

Can I use some of the information from this blog post above if I give a link back to your website?

Thanks,
Charlie

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.