3
\$\begingroup\$

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;
} 
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Apr 2 '19 at 10:33
4
\$\begingroup\$

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;
\$\endgroup\$
3
  • \$\begingroup\$ I don't really know this type of operator: ??. i have a parse error unexpected '?' on $_SESSION['lang'] = $langs[$lang] ?? $defaultLang; \$\endgroup\$
    – Ogum
    Apr 2 '19 at 9:29
  • \$\begingroup\$ I've update my answer to provide a null coalescing operator replacement. \$\endgroup\$ Apr 2 '19 at 9:39
  • \$\begingroup\$ @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. \$\endgroup\$
    – Script47
    Apr 2 '19 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.