Title rewritten to: "Undefined variable in PHP array"
P粉432930081
P粉432930081 2023-09-05 20:13:14
0
1
691
<p>I am trying to get the country code using php. I use the following code, but get this warning: </p> <blockquote> <p>Undefined index: country_code</p> </blockquote> <pre class="brush:php;toolbar:false;">function getIP($ip) { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://ipwho.is/".$ip, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "utf8", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "accept: application/json", "content-type: application/json" ), )); $response = curl_exec($curl); $err = curl_error($curl); //print_r($response); curl_close($curl); if ($err) { return "cURL Error #:" . $err; } else { return $response; } } function isIndo($ip) { $ip = getIP($ip); $info = json_decode($ip, true); //print_r($info); if( $info['country_code'] == "ID" ) { return true; } else { return false; } }</pre> <p>What went wrong? </p>
P粉432930081
P粉432930081

reply all(1)
P粉561749334

Have you tried isset()?

Before accessing an array key, try to check if it exists

if( isset($info['country_code']) && $info['country_code'] == "ID" ) {
    return true;
}

Link to isset()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template