简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM