TransWikia.com

Code optimization, adaptation to a large number of conditions

Magento Asked on November 8, 2021

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);
        }

One Answer

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;
        }
    }

Answered by Afreen Sheikh on November 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP