search

Home  >  Q&A  >  body text

Title rewritten to: "Undefined variable in PHP array"

<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粉432930081P粉432930081446 days ago689

reply all(1)I'll reply

  • P粉561749334

    P粉5617493342023-09-06 00:18:16

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

    reply
    0
  • Cancelreply