简体   繁体   中英

Compare key in multidimensional array

I'm trying to set a cookie depending on if the users country code is available in an array.

$Countries = array(
    "SE" => "swe",
    "DEU" => "ger",
    "NLD" => "dut",
    "HRV" => "cro",
    "FRA" => "fr",
    "HUN" => "hun",
);

foreach($Countries as $Key => $Value) {
    if($this->Country($_SERVER["REMOTE_ADDR"]) == $Key) {
        setcookie('LanguageCookie', $Value, time()+(10 * 365 * 24 * 60 * 60));
        setcookie('LanguageIsNative', true, time()+(10 * 365 * 24 * 60 * 60), '/');
        break;
    } else {
        setcookie('LanguageCookie', $Configuration["Config"]["DefaultLanguage"], time()+(10 * 365 * 24 * 60 * 60));
        break;
    }
}

Now, If my country code is "SE" it will work and it will set the cookie LanguageCookie to swe . But if my country code is anything below "SE" in the array, for example "HRV" , it will fail and run the else block (keep in mind that if the country code doesnt exist in the array, it should run the else block).

I break the loop because other it'd just go on and in the end just run the else block, even if the country code exists.

How can this be fixed?

You don't need to use a foreach loop to achieve this.

// Get the country code
$country = $this->country($_SERVER['REMOTE_ADDR']);

// Set cookies
if (isset($countries[$country])) {
    setcookie('LanguageCookie', $countries[$country], time()+(10 * 365 * 24 * 60 * 60));
    setcookie('LanguageIsNative', true, time()+(10 * 365 * 24 * 60 * 60), '/');
} else {
    setcookie('LanguageCookie', $Configuration["Config"]["DefaultLanguage"], time()+(10 * 365 * 24 * 60 * 60));
}

The problem is, the else block should be executed once after the loop - if the condition was never met. This could be achieved, by setting a flag inside the loop.

$found = false;
foreach($Countries as $Key => $Value) {
    if($this->Country($_SERVER["REMOTE_ADDR"]) == $Key) {
        setcookie('LanguageCookie', $Value, time()+(10 * 365 * 24 * 60 * 60));
        setcookie('LanguageIsNative', true, time()+(10 * 365 * 24 * 60 * 60), '/');
        $found = true;
        break;
    }
}
if (!$found) {
    setcookie('LanguageCookie', $Configuration["Config"]["DefaultLanguage"], time()+(10 * 365 * 24 * 60 * 60));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM