P. Nick
P. Nick

Reputation: 991

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?

Upvotes: 0

Views: 56

Answers (2)

fubar
fubar

Reputation: 17378

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

Upvotes: 3

Philipp
Philipp

Reputation: 15629

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

Upvotes: 1

Related Questions