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.
source to share
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
.
source to share
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.
source to share