I need to display site visitor's continent. I am using geoip functionality to pull 2 letter code, which I can get to work very easily. However, just displaying 'AS' for Asia to the site visitor is clearly undesirable. So I'm trying to convert that. This is what I am trying to do. . .
<?php
$continent = geoip_continent_code_by_name($_SERVER['REMOTE_ADDR']);
$africa = array('AF');
$antarctica = array('AN');
$asia = array('AS');
$europe = array('EU');
$northamerica = array('NA');
$oceania = array('OC');
$southamerica = array('SA');
if ($africa) {
echo 'Africa';
}
elseif ($antarctica) {
echo 'Antarctica';
}
elseif ($asia) {
echo 'Asia';
}
elseif ($europe) {
echo 'Europe';
}
elseif ($northamerica) {
echo 'North America';
}
elseif ($oceania) {
echo 'Australia and Oceania';
}
elseif ($southamerica) {
echo 'South America';
}
else {
echo '';
}
?>
It just displays 'Africa' no matter where the site visitor, so it's getting stuck there. I'm reading though PHP tutorials but can't figure out what I'm doing wrong. My if, else and elsifs look good as far as I can tell.
My Answer:
The issue in your code is that you are not properly checking the value of the $continent variable. You are checking if $africa, $antarctica, $asia, etc. are true, which they always will be because they are arrays with values in them.
You need to change your if statements to check if $continent is equal to the 2 letter continent code. Here is the corrected code:
php
$continent = geoip_continent_code_by_name($_SERVER['REMOTE_ADDR']);
if ($continent == 'AF') {
echo 'Africa';
}
elseif ($continent == 'AN') {
echo 'Antarctica';
}
elseif ($continent == 'AS') {
echo 'Asia';
}
elseif ($continent == 'EU') {
echo 'Europe';
}
elseif ($continent == 'NA') {
echo 'North America';
}
elseif ($continent == 'OC') {
echo 'Australia and Oceania';
}
elseif ($continent == 'SA') {
echo 'South America';
}
else {
echo '';
}
?>
Now, the code will correctly display the full continent name based on the 2 letter code retrieved from the geoip functionality.
Rate this post
4 of 5 based on 7400 votesComments