为什么会出现此错误注意:未定义的索引:host


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

我的示例代码在这里

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 />";
}

当我尝试这个代码时,我得到了这样的错误:注意:未定义的索引:host-in…我的代码出了什么问题?请给我一些帮助代码,提前谢谢。

在假设数组存在之前,需要使用isset检查数组是否包含'host'的条目:

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

或者,您可以使用@来抑制检查中的警告。

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

然而,当两者都不存在时,您需要仔细检查后者是否按您的意愿工作。

更新:正如其他人所指出的,还有array_key_exists。它将处理null数组值,而isset将为null值返回false

正如其他人所回答的,isset()array_key_exists()都将在这里工作。isset()很好,因为它实际上可以接受多个参数:

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

仅当设置了所有参数时才返回true

您可以使用array_key_exists 来确定数组是否具有名为"host"的索引

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

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