Last active
February 24, 2022 10:13
-
-
Save LucaRosaldi/5676962 to your computer and use it in GitHub Desktop.
PHP: Get Browser Language, optionally passing a list of available languages.
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, optionally passing a list of available languages. | |
* | |
* @param [array] $available_languages Available languages for the site | |
* @param [string] $default Default language for the site | |
* @return [string] Language code | |
*/ | |
function get_browser_language_code( $available_languages = [], $default = 'en' ) : string | |
{ | |
$browser_languages = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] ); | |
if ( empty( $available_languages ) ) { | |
return substr( $browser_languages[ 0 ], 0, 2 ); | |
} | |
foreach ( $browser_languages as $language ) { | |
$language = substr( $language, 0, 2 ); | |
if ( in_array( $language, $available_languages ) ) { | |
return $language; | |
} | |
} | |
return $default; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Suggestion for line 15:
return substr( $langs[0], 0, 2 );
And I would use
!empty()
instead ofisset()
.