0
if (isset($_GET['language']) && !empty($_GET['language'] && $_SESSION['language'] !== $_GET['language'])) {
    if ($_GET['language'] === 'en') {
      $_SESSION['language'] = 'en';
    } elseif ($_GET['language'] === 'ar') {
      $_SESSION['language'] = 'ar';
    } elseif ($_GET['language'] === 'de') {
      $_SESSION['language'] = 'de';
    } else {
      $_SESSION['language'] = $default_language;
    }
  }

I would like to loop only elseif statements. Is there away to achieve this?

2
  • Looks like you could just set $_SESSION['language'] = $_GET['language'] if $_GET['language'] is set. No need for lots of ifs. If you want to make sure $_GET['language'] can only take certain values use in_​array Commented Jun 21, 2021 at 21:49
  • Agreed, your example is a big pile of redundant hard-coding Commented Jun 21, 2021 at 21:50

2 Answers 2

1

There's no need for a loop here. If your intention is to whitelist the available languages then put a list in an array and use in_array():

$languages = ['ar','de','en'];
if (isset($_GET['language']) && in_array($_GET['language'], $languages)) {
    $_SESSION['language'] = $_GET['language'];
} else {
    $_SESSION['language'] = $default_language;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to do isset and empty as empty will do that for you.

This also checks if the language is in one of the specific ones (using in_array) and if it isn't then it uses the default...

if (!empty($_GET['language']) && $_SESSION['language'] !== $_GET['language']) {
    $_SESSION['language'] = in_array($_GET['language'], ['en', 'ar', 'de'])
            ? $_GET['language'] : $default_language;
}

1 Comment

Need to close the empty sooner. !empty($_GET['language'])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.