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

my example 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 to execute this code, I got this error: Note: Undefined index: host in ... What's wrong in my code? Please offer me the help code, thanks in Advance.

+3


source to share


3 answers


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 scan.



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

      

However, you will need to double check that the latter works as you want when both are missing.

Update: As others have pointed out, there is also array_key_exists

. It will process array values null

whereas it isset

returns false

for values null

.

+2


source


As others have answered isset()

and array_key_exists()

will work here. isset()

nice because it can take multiple arguments:

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

// same as

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

      



Returns true

only if all arguments are set.

+2


source


you can find out if the array has an index named "host" with 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

0


source







All Articles