Potion Potion - 7 days ago 6
PHP Question

How to Check if find returns as null?

Im working a page thats dynamic and sometimes it has elements and sometimes it does not.



$data2 = $data1->find("tr td");





Is there a way I can check if the code below returns null? It works fine when it is found but it throws the error when it is not:


Fatal error: Call to a member function find() on null in /Applications/MAMP/htdocs/rs/login.php on line 175


full function code:



$url = "http://services.runescape.com/m=hiscore_oldschool/hiscorepersonal.ws?user1=";
$link = $url . $name;
$html = file_get_html($link);

$data1 = $html->find("div[id=contentHiscores] table tbody",0);
$data2 = $data1->find("tr td");

$data2 = (!empty($data1)) ? $data1->find("tr td") : null;
if(empty($data2)){
echo 'empty';
}else{
echo 'do something';
}




Answer

Here the problem in $data1 variable. When $data1 is null it throws error.

$url = "http://services.runescape.com/m=hiscore_oldschool/hiscorepersonal.ws?user1=";
$link = $url . $name;
$html = file_get_html($link);

$data1 = (!empty($html)) ? $html->find("div[id=contentHiscores] table tbody",0) : null; 
$data2 = (!empty($data1)) ? $data1->find("tr td") : null;

if(empty($data2)){
    echo 'empty';
}else{
    echo 'do something';
}
Comments