Detect browser language

<? function get_client_language($availableLanguages, $default='en'){ if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']); foreach ($langs as $value){ $choice=substr($value,0,2); if(in_array($choice, $availableLanguages)){ return $choice; } } } return $default; }
If your website is multilingual, it can be useful to detect the browser language to use this language as the default. The code will return the language used by the client’s browser.

1 Response

Unfortunately for cases like `zh-TW` vs. `zh-CN` this method doesn't work well based on `substr($value,0,2)`. Take this sample; `en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4,es;q=0.2,it;q=0.2,fr;q=0.2`. Even if you match `zh` that's not exactly what you need. You really want the 5 char version. In the case of `en-US` it totally works. I haven't tested your version but from my own experience supporting only `zh-TW` on it seems you need to consider 5 chars. I had created a subset of this example at but got lazy with the pref matching. ;-)

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.