# Language switch based on parameters and session state

I use this to set language session for navigation. Someone said that this switch is too cumbersome. Why? Is there an easier way?

$defaultLang = 'it'; if (!empty($_GET["lang"])) {
switch (strtolower($_GET["lang"])) { case "en":$_SESSION['lang'] = 'gb';
break;
case "tr":

$_SESSION['lang'] = 'tr'; break; default:$_SESSION['lang'] = $defaultLang; break; } } if (empty($_SESSION["lang"])) {
$_SESSION["lang"] =$defaultLang;
}

• Please note that mickmackusa changed his answer, to make it do exactly the same as the code in your question, after you had accepted his answer as the best possible. You might need to correct your own code, to reflect this change, if you copied his code. Apr 2 '19 at 10:33

Yes. Definitely. You can use a lookup array.

$langs = [ 'en' => 'gb', 'tr' => 'tr', ];$defaultLang = 'it';

if (isset($_GET['lang'])) {$lang = strtolower($_GET['lang']);$_SESSION['lang'] = $langs[$lang] ?? $defaultLang; } elseif (!isset($_SESSION['lang'])) {  // meaning, no $_GET['lang'] and no$_SESSION['lang']
$_SESSION['lang'] =$defaultLang;
}
// if there is no $_GET['lang'] and there is a$_SESSION['lang'], then nothing to update


A lookup array is concise and a breeze to maintain. You only need to update the lookup or the fallback value; never the processing block.

?? is the null coalescing operator, so if the lang value is not found in the lookup, the fallback value will be used.

If your php version is not over 7 (then I urge you to upgrade) then you will need a longer condition syntax.

$_SESSION['lang'] = isset($langs[$lang]) ?$langs[$lang] :$defaultLang;

• I don't really know this type of operator: ??. i have a parse error unexpected '?' on $_SESSION['lang'] =$langs[$lang] ??$defaultLang;
– Ogum
Apr 2 '19 at 9:29
• I've update my answer to provide a null coalescing operator replacement. Apr 2 '19 at 9:39
• @Ogum the alternative name for it is the 'isset ternary because of what it does, it is essentially performing an isset check without the need for the true` condition. Apr 2 '19 at 10:48