sandman human man
sandman human man

Reputation: 65

How can I select first array if country not in array?

I am using the php geoip_country_code_by_name function to serve up different content for different countries from an array which looks like this:

<?php

    $content = array(
        'GB' => array(
            'meta_description'  => "Description is here",
            'social_title'      => "Title here",
            'country_content_js'   => "js/index.js",
        ),
        'BR' => array(
            'meta_description'  => "Different Description is here",
            'social_title'      => "Another Title here",
            'country_content_js'   => "js/index-2.js",
        ),
    );

?>

How can I check if the users country is in the array and if not set 'GB' as the default?

I am using this to check for the country:

$country = ( isset($_GET['country']) && !empty($_GET['country']) ? $_GET['country'] : ( isset($_SESSION['country']) && !empty($_SESSION['country']) ? $_SESSION['country'] : ( isset($_COOKIE['country']) && !empty($_COOKIE['country']) ? $_COOKIE['country'] : geoip_country_code_by_name(ip()) ) ) );

Upvotes: 1

Views: 238

Answers (3)

Ahmad Alhusainy
Ahmad Alhusainy

Reputation: 54

First : i Added a new variable for default country code .. ($defaultCountry = 'GB');

Second : try to get the country code from (get , session , cookie ,
geoip_country_code_by_name or default as assigned).

Finally : check if the country code exists in the $content array() otherwise return the default country ..

 $defaultCountry = 'GB';
if(isset($_GET['country']) && !empty($_GET['country'])){
    $country =$_GET['country'];
}elseif(isset($_SESSION['country']) && !empty($_SESSION['country'])){
    $country =$_SESSION['country'];
}elseif(isset($_COOKIE['country']) && !empty($_COOKIE['country'])){
    $country =$_COOKIE['country'];
}elseif($value = geoip_country_code_by_name(ip())){
    $country = $value;
}else{
    $country = $defaultCountry;
}

if(isset($content[$country])){
    $country =$content[$country];
}else{
    $country = $content[$defaultCountry];//Default ..
}

Upvotes: 0

Passionate Coder
Passionate Coder

Reputation: 7294

You can check it with ternary operator also

countryArr  = array();
$countryArr = array_key_exists($code,$content) ? $content[$code] : $content['GB'];

Upvotes: 0

Alok Patel
Alok Patel

Reputation: 8022

First check if the country code is in the $content array as a key or not, if not serve the first array as a default. To check if the key exists in array or not use array_key_exists().

Like this,

$countrycode="IN";
if(!array_key_exists($countrycode,$content)) {
   $countryarray=$content[0];
} else {
   $countryarray=$content[$countrycode];
}

Above code will return country's content if available or first if not found in an array.

Upvotes: 1

Related Questions