Lyndon Penson
Lyndon Penson

Reputation: 65

PHP compare strings - country from IP address and fixed value

I have this php which determines the country from IP address, that part works. It is then supposed to say "hello UK" if the country = "United Kingdom" however it returns "not uk" even though when I echo the $location value it says United Kingdom.

I wondered if it was due to the variable type but I did echo gettype ($location); and it returned string, I believe I am comparing it to a string and cannot now work out why I get the unexpected result.

What is wrong with my php comparison?

Thanks

$IP = "{$_SERVER['REMOTE_ADDR']}";  
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$IP)) ;
$location = $query ['country'];
echo $location;
if  ($location == 'United Kingdom') {
echo 'hello UK';
}else{
echo 'not uk';}

Upvotes: 0

Views: 131

Answers (2)

drmonkeyninja
drmonkeyninja

Reputation: 8540

Your example code works for me, but you should make sure you trim any whitespace surrounding the country name before doing the comparison:-

trim($country) === 'United Kingdom'

It might also be worth checking against a lowercase string too:-

strtolower(trim($country)) === 'united kingdom'

If that's still not working use var_dump() rather than echo to check the value, that should make any inconsistencies more obvious as it will show the string in quotes:-

var_dump($country);

Upvotes: 0

Andrew Rayner
Andrew Rayner

Reputation: 1064

Use === when evaluating a string to string comparison, which is what this is.

However it sounds to me that $location is not equal to "United Kingdom" when it runs the check.

Upvotes: -1

Related Questions