dopo forech aggiungi un if

codice:
if ($str!="" && $data!="") {
  echo("<a href=\"".$str."\">".$data."</a>
");
}