Skip to content

Instantly share code, notes, and snippets.

@ionurboz
Forked from joke2k/get-browser-language.php
Created May 3, 2023 14:23
Show Gist options
  • Save ionurboz/edae9a30585a93110c8460983aed5dbf to your computer and use it in GitHub Desktop.
Save ionurboz/edae9a30585a93110c8460983aed5dbf to your computer and use it in GitHub Desktop.
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 empty( $langs ) ? $default : $langs[ 0 ];
}
foreach ( $langs as $lang ){
$lang = substr( $lang, 0, 2 );
if( in_array( $lang, $available ) ) {
return $lang;
}
}
}
return $default;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment