Skip to content

Instantly share code, notes, and snippets.

@LucaRosaldi
Last active February 24, 2022 10:13
Show Gist options
  • Save LucaRosaldi/5676962 to your computer and use it in GitHub Desktop.
Save LucaRosaldi/5676962 to your computer and use it in GitHub Desktop.
PHP: Get Browser Language, optionally passing a list of available languages.
<?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;
}
@Adrian-S
Copy link

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