Yii::$app->request->getPreferredLanguage() is not returning the correct language of my browser.

My browser is in French but Yii::$app->request->getPreferredLanguage() is return string ‘en-US’ (length=5) when I dump it to see its value. What is wrong? I was expecting ‘fr-FR’.

What I want is to use the language of the browser when the user load the website for the first time; after that he can choose another language. So I thought with Yii::$app->request->getPreferredLanguage() I can get the browser language.

You need to pass the array of available app languages to this method like

Yii::$app->request->getPreferredLanguage(['en-US', 'fr-FR'])

then it can check if $_SERVER[‘HTTP_ACCEPT_LANGUAGE’] contains one of the languages it can use.

Without the array it only returns application default language.

Does it automatically do the correspondance between 5 length string(‘fr-FR’) with 2 length string(‘fr’)?

It does.

Yes it does!!! My below post should be deleted; but the system is prompting an error when I want to delete it. I would also like to know if when it doesn’t find matching language does it return the application default language?

If the language is not there from what I have seen it seems like it choose a language that exists in the list following the preference order of the browser user.


Thx for sharing this code. I didn’t know this exists.