Is there an easier way?

I’m making my site multilanguage and are choosing the language by 2 default. Either the browser language or the language the user has entered like this:

if(!$language){
	if (substr($lang, 0, 2) == 'da') {
		// Danish language //
	} else {
		// In english //
	}
} else {
	if ($language == 'da') { 
		// Danish language //
	} else {
		// In english //
	}
}

Couldnt this be done easier?

Thanks in advance…


<?php
$languages = array(
  'kr',
  'da'
);

$language = 'ch';

if(!in_array($language, $languages)){
  $language = 'en';
}

Does this take care of both the browser and the cookie?

No, but neither did yours. :slight_smile:

I’d personally use a switch!


$Language = $_GET['l'];

switch($Language)
   {
   case 'en':
      //Do something here
      break;
   case 'fr':
      //French
      break;
   default:
      //Anything else here - EG error - language not supported
   }


Hmmm. thought it did… How do I then first take in consideration if a user has set the cookie, and if not find out what the browsers language is and take action after that?

What about something like…


<?php
function getLanguage(){
  
  if(array_key_exists('lang', $_COOKIE)){
    return $_COOKIE['lang'];
  }
  
  if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER){
    if(2 <= strlen($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
      return substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    }
  }
  
  return '';
}

$languages = array(
  'kr',
  'da'
);

if(!in_array(getLanguage(), $languages)){
  $language = 'en';
}