1

I need to make a condition, if the server code has a certain value, then it will set the appropriate currency. I did this via an if else condition. But if there are many 5+ conditions, it will look wrong. Help optimise and shorten the code by using an array

        $de = 'de';
        $currencyEuro = 'EUR';

        $uk = 'uk';
        $currencyPound = 'GBP';

        if ($this->getStoreCurrency() !== $currencyEuro && $_SERVER['HTTP_LANGUAGE'] == $de) {
            $this->storeManager->getStore()->setCurrentCurrencyCode($currencyEuro);
        } elseif ($this->getStoreCurrency() !== $currencyPound && $_SERVER['HTTP_LANGUAGE'] == $uk) {
            $this->storeManager->getStore()->setCurrentCurrencyCode($currencyPound);
        }

1 Answer 1

1

As per your code you can use this code for simplicity

    $array = [
        'de' => 'EUR',
        'uk' => 'GBP'
    ];
    $currency = $this->getStoreCurrency();

    foreach ($array as $k => $value) {
        if ($currency!== $value && $_SERVER['HTTP_LANGUAGE'] == $k) {
            $this->storeManager->getStore()->setCurrentCurrencyCode($value);
            break;
        }
    }
2
  • and if I need to use several languages for the euro, do I need to duplicate or can this be simplified? 'de' => 'EUR', 'fr' => 'EUR', ...
    – Alice
    Jul 21, 2020 at 14:07
  • yes. you can use it as you've mentioned. Jul 21, 2020 at 17:34

Your Answer

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

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