Search

Laravel String Helper Function: str_plural

November 16, 2016 —John Koster

The plural helper method will attempt to return a plural version of the given $value. It does this through a series of specialized internal functions, that will not be covered in great detail here. This helper method will apply general rules to strings ending in common character sequences, handle special cases and will not attempt some very specific strings. The change in a word, such as to show tense, or the number of items, is called an inflection.

The signature for the plural helper function is:

plural($value, $count = 2)

doctrine/inflector

Previous versions of Laravel managed word inflections itself. Starting with version 5, Laravel now uses the doctrine/inflector package. This package is used by the Illuminate\Support\Pluralizer class, which is utilized by both the plural and the singular method.

The method takes the $value that should be pluralized, and the $count of the items. If the $count is equal to 1, the original $value is returned.

1use Illuminate\Support\Str;
2 
3// cow
4echo Str::plural('cow', 1);
5 
6// cows
7echo Str::plural('cows');
8 
9// person
10echo Str::plural('person', 1);
11 
12// people
13echo Str::plural('person');

Assuming the following messages array:

1// The user's messages.
2$messages = [
3 'You have a meeting on Saturday.',
4 'Your inbox is 90% full',
5 'Do not eat yellow snow'
6];

We could display the number of messages to the user like so:

1use Illuminate\Support\Str;
2 
3$messageCount = count($messages);
4 
5echo 'You have '.$messageCount.' unread '.
6 Str::plural('message',$messageCount);

If the user had one message, the above example would output:

1You have 1 unread message.

Since the $messages array has 3 items in it, the user would see this:

1You have 3 unread messages.

#str_plural($value, $count = 2)

The str_plural function is a shortcut to calling Str::plural. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.