CakePHP Pluralize Helper

Posted by Tim Koschützki, on Nov 02, 2007 - in PHP & CakePHP » Views & Helpers

Hey folks,

here is a small helper file for the CakePHP framework that will help you turn a subject into the pluralized form depending on a parameter. Here is the code:

php
  1.   class PluralHelper extends Helper {
  2.     function ize($s, $c) {
  3.       if($c==0 || $c > 1) {
  4.         $inflect = new Inflector();
  5.         return $c . ' ' . $inflect->pluralize($s);
  6.       } else{
  7.         return $c . ' ' . $s;
  8.       }
  9.     }
  10.   }

Save the code into a file called "plural.php" and place it in app/views/helpers/. After you activated the helper in your controller(s), you can use it as follows in your views:

php
  1. echo $plural->ize('article', count($articles));

..which will output "article" if the second parameter is 1, or "articles" if it is 0 or > 1. This is neat to display text as in "You have writte SOME_NUM article(s) already". You get the idea. It uses Cake's Infelctor class, so that special cases like "baby/babies" are taken care of as well.

One note: If you have a CommonHelper already, it would be good to copy the code into a "pluralize" method in the CommonHelper instead. Why? Because as of now the PluralHelper only has this one method and there does not justify to be a class on its own. :]

Print this Post | Digg This | Stumble It | Delicious

3 Comments

[...] Koschuetzki has another CakePHP tip to share on his blog today - a helper that lets you pluralize a word easily. Here is a small helper file [...]

Tarique Sani on Nov 06, 2007:

Nice - I like the $plural->ize construct :)

PHP Encoder on Feb 19, 2008:

Cool! :)
I like $plural too