Skip to content

Novis\Intl\Locale::negotiate

Chooses the language for a page from the Accept-Language header a browser sends.

Locale::negotiate takes the header's value, the list of locales your site offers, and a default. It returns the offered locale that the reader wants most. The header lists languages with weights, such as "fr;q=0.5, de, en;q=0.8". A language with no weight has the weight 1. For that header and the offered list ["en", "de", "fr"], the result is "de".

A regional tag matches its language. "de-AT" and "de-CH" both match an offered "de". The result is always written the way your list writes it, so "pt-br" in the header gives "pt-BR" when you offer "pt-BR".

An empty header, a header that is not valid, and a header that matches nothing all return the default. The method does not throw for them, because the header comes from the reader and may contain anything. It throws a LogicError when a tag in your own offered list is not valid.

Good to know: the result is always one of your offered locales or the default. You can pass it to the other Novis\Intl classes without checking it again.

Parameters

  • $acceptLanguagestring
  • $offeredarray<string>
  • $defaultstring

Return value

Returns string.

Examples

Pick a language for a page

<?nvs
// Shows how to choose a page's language from the browser's `Accept-Language` header.
use Novis\Intl\Locale;
array<string> $offered = ['en', 'de', 'fr'];
// The reader prefers Swiss German, then German, then English.
// "de-CH" matches the offered "de". This prints de.
echo Locale::negotiate('de-CH, de;q=0.9, en;q=0.5', $offered, 'en'), "\n";
Output
de

The weight decides

<?nvs
// Shows that the language with the highest weight wins, not the first one in the header.
use Novis\Intl\Locale;
array<string> $offered = ['en', 'fr'];
// French has the weight 0.5 and English has 0.8. This prints en.
echo Locale::negotiate('fr;q=0.5, en;q=0.8', $offered, 'fr'), "\n";
// Japanese is not offered, so the next language is used. This prints fr.
echo Locale::negotiate('ja, fr;q=0.4', $offered, 'en'), "\n";
Output
en
fr

A bad header gives the default

<?nvs
// Shows that a header with no usable language returns the default.
use Novis\Intl\Locale;
array<string> $offered = ['en', 'de'];
array<string> $headers = ['', 'not a tag', 'ja'];
// The first header is empty, the second is not valid, and the third matches nothing.
// None of them throws. This prints de three times.
foreach ($headers as string $header) {
echo Locale::negotiate($header, $offered, 'de'), "\n";
}
Output
de
de
de