0

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?

2 Answers 2

3

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was trying to find a way without using a loop, never got around, so thanks for sharing this!
1

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

3 Comments

I understand now. This makes much more sense, thank you!
of course this is just to explain your problem - you should consider to remove the loop and just use isset
Yeah I understand. I was only looking for what I was doing wrong. I'm always looking for ways to improve my code.

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.