简体   繁体   中英

Why am I getting this error Notice: Undefined index: host

my sample code is here

include 'simple_html_dom.php';
function get_all_links($url){
    global $host;
    $html = new simple_html_dom();
    $html->load(file_get_contents($url));

    foreach($html->find('a') as $a){
        $host1 = parse_url($a->href);
        $host = parse_url($url);
            if($host1['host'] == $host['host']){
                    $data[] = $a->href;
            }
    }
    return $data;

}
$links = get_all_links("http://www.example.com/");

foreach($links as $link){
   echo $link."<br />";
}

When I try this code, I got this error: Notice: Undefined index: host in... What's wrong in my code? Please suggest me some helping code, Thanks in Advance.

You need to check if the arrays contain entries for 'host' using isset before assuming they exist:

if (isset($host1['host']) && isset($host['host']) 
        && $host1['host'] == $host['host']) {

Or you can use @ to suppress warnings from the check.

if (@$host1['host'] == @$host['host']) {

However, you'll need to double-check that the latter works as you desire when both are missing.

Update: As the others pointed out there is also array_key_exists . It will handle null array values whereas isset returns false for null values.

As others have answered, both isset() and array_key_exists() will work here. isset() is nice, because it can actually take multiple arguments:

if (isset($array[0], $array[1], $array[2]))
{
    // ...
}

// same as

if (isset($array[0]) && isset($array[1]) && isset($array[2]))
{
    // ...
}

Returning true only if all arguments are set.

you can find out if an array has an index called "host" using array_key_exists

if (array_key_exists($host, "host") && array_key_exists($host1, "host") && ...)

http://us3.php.net/manual/en/function.array-key-exists.php

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