Forked from LucaRosaldi/get-browser-language-code.php
Created
January 21, 2022 19:58
-
-
Save gerardojbaez/93677f337f72e60b39c48d8cca3bfcdf to your computer and use it in GitHub Desktop.
PHP: Detect Browser Language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment