February 19, 2018 —John Koster
The trans_choice
helper function can be used to translate a line of text that is dependent on a number of items in a collection. For example, if you were developing an application to retrieve messages from an IMAP inbox, you might want the ability to display "You have 1 unread message" vs. "You have 3 unread messages". The trans_choice
method, like the trans
method, accepts an array of replacements that can be used to dynamically build out the translated string.
Replacements are passed as a key/value pair. The replacement keys will be matched to any placeholders within the translation string. Placeholders begin with a single colon (:
) followed by a name and a space. For example, in the validation.php
language file, the following lines can be found:
1<?php 2 3return [ 4 5 // ... 6 7 'accepted' => 'The :attribute must be accepted.', 8 'active_url' => 'The :attribute is not a valid URL.', 9 10 // ...11 12];
In the above translation lines, :attribute
is a placeholder that can be replaced using the $parameters
parameter. The following code examples will demonstrate the results of the $parameters
parameter.
The signature of the trans_choice
method is:
1function trans_choice(2 $key, // The translation text key.3 $number, // The number of items.4 array $replace = [], // The replacements to make.5 $locale = null // An optional locale to use.6);
For this section, we will create a new file at /resources/lang/en/plural.php
:
1<?php2 3return [4 'books' => 'There is one book.|There are :count books.',5];
We can observe the results of the trans_choice
method with the following examples
1// Get the translated text for one item.2$oneItem = trans_choice('plural.books', 1);3 4// Get the translated text for two items.5$multipleItems = trans_choice('plural.books', 2);
Important: The $number
parameter is required every time the trans_choice
method is invoked even if you are translating a collection containing one item.
After the above code has executed, the $oneItem
variable would contain the value There is one book.
and the $multipleItems
variable would contain the value There are 2 books.
.
∎
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.