Welcome Guest, Not a member yet? Register   Sign In
Simple extension of the CI inflector helper
#1

[eluser]Kobus M[/eluser]
Hi,

I had the need to create a new helper that extends the functionality of the CI inflector helper. I hope this helps someone. It is not rocket science, but has helped me a lot to simplify my coding somewhat.

Code:
function my_inflector($count, $word, $showcount = true)
{
    if ($count > 1) // Given more than 1 in the count.
    {
        if ($showcount)
        {
            if (substr($word, -2) == 'ss')
            {
                return $count . ' ' . plural($word, true);
            }
            return $count . ' ' . plural($word);
        }
        return plural($word);
    }
    else // Given only one for the count.
    {
        if ($showcount)
        {
            if (substr($word, -2) == 'ss')
            {
                return $count . ' ' . $word;
            }
            return $count . ' ' . singular($word);
        }
        return singular($word);
    }
}

The purpose of this is to let the function decide whether to use plural or singular form, based on parameters passed. This is useful when you determine the count of items at runtime.

For example:

If you do a search and found 3 records (the count saved in variable $count) that match the set, you can call the function as follows:

Code:
my_inflector($count, 'records')

you will get a return of '3 records'.

Code:
my_inflector($count, 'records', false)

will return 'records'.

If you found only 1 record, and you call the following:

Code:
my_inflector($count, 'records')

you will get '1 record'.

Please note:

I recommend providing the plural form of the word in the function, as per the reasons below:

In words ending with a double 's', i.e., my_inflector($count, 'addresses'); because of the fact that I have only built in a very BASIC English language rule for singular form; I assume that words ending in 'ss' if the count is only 1, is already in singular form (thus, "address" will return as "address" and not "addres"). I have not found a single test case so far that is wrong with providing the word in plural form to the function.

Furthermore, I am assuming that if a word is to be changed into plural form, and ends in 'ss', I force the addition of 'es' instead of 's' to the word, for example, address. Using singular form of bus will still result in buss which is incorrect; it should be buses. Entering it as buses in the function, returns the correct result when converting to singular form.

There is a reason why not even Office Suites can get the whole grammar thing correct in all situations - it is complex.

Kobus




Theme © iAndrew 2016 - Forum software by © MyBB