November 16, 2016 —John Koster
The trans_choice
helper function is used to pluralize a given $id
, translating it for the given $locale
. The choice
method accepts the $number
of some collection of objects that it should use when making pluralization decisions. Like the trans
helper function, it also accepts and array of replacements, using the $parameters
array.
The signature for the trans_choice
helper function is:
trans_choice($id, $number, array $parameters = [], $domain = 'messages', $locale = null)
Assuming the following group file is located at /resource/lang/en/plural.php
:
1<?php2 3return [4 'books' => 'There is one book.|There are :count many books.',5];
It should be noted that pluralized strings allow for multiple messages to be stored in one translation line. Messages are separated by the |
character, and are ordered such that the message that corresponds to the lower $number
appear first and messages that appear for any higher $number
appear sequentially afterwards.
The following code example would select the first message:
1// There is one book.2trans_choice('plural.books', 1);
The following code example would select the second message:
1// There are 4 books.2trans_choice('plural.books', 4, ['choice' => 4]);
The following code examples highlight some more ways the trans_choice
helper function can be called, and ways they will mostly appear within applications:
1// There are 4 books.2trans_choice('plural.books', 4, ['choice' => 4]);3 4// There is one book.5trans_choice('plural.books', 1, ['choice' => 1]);
∎
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.