[英]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: 在假定存在之前,您需要使用isset
检查数组是否包含'host'
条目:
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
. 更新:正如其他人指出的那样,还有array_key_exists
。 It will handle null
array values whereas isset
returns false
for null
values. 它将处理null
数组值,而isset
对null
值返回false
。
As others have answered, both isset()
and array_key_exists()
will work here. 正如其他人已经回答的那样, isset()
和array_key_exists()
都可以在这里工作。 isset()
is nice, because it can actually take multiple arguments: isset()
很好,因为它实际上可以采用多个参数:
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. 仅在设置了所有参数时返回true
。
you can find out if an array has an index called "host" using array_key_exists
你可以使用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 http://us3.php.net/manual/en/function.array-key-exists.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.