Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP: Detect Browser Language
<?php
/**
* Get browser language, given an array of avalaible languages.
*
* @param [array] $availableLanguages Avalaible languages for the site
* @param [string] $default Default language for the site
* @return [string] Language code/prefix
*/
function get_browser_language( $available = [], $default = 'en' ) {
if ( isset( $_SERVER[ 'HTTP_ACCEPT_LANGUAGE' ] ) ) {
$langs = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
if ( empty( $available ) ) {
return $langs[ 0 ];
}
foreach ( $langs as $lang ){
$lang = substr( $lang, 0, 2 );
if( in_array( $lang, $available ) ) {
return $lang;
}
}
}
return $default;
}
@Adrian-S

This comment has been minimized.

Copy link

@Adrian-S Adrian-S commented Sep 7, 2018

Suggestion for line 15: return substr( $langs[0], 0, 2 );
And I would use !empty() instead of isset().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment