Dont declare functions embedded within other functions.
In this case, you can just manually make chk() inline.
Dont evaluate a function with the exact same parameters and state more than once.
A possible solution might be:
function get_animals($code,$animal)
{
db_connect('pets');
$all_animals = array(); //in case array is never actually initialised otherwise
$result = mysql_query("query");
while ( $row = mysql_fetch_row($result) )
{
$temp = mysql_query("SELECT * FROM {$row[0]} WHERE code = '$code'");
if (mysql_num_rows($temp) == 1 || $row[0] == $animal)
{
$chk = "checked";
}
else
{
$chk = "";
}
echo "<input type='checkbox' name='pets[]' value='$row[0]' ".$chk."/>".$row[0]."<br/>\n";
if ($chk == "checked")
{
$all_animals[] = $row[0];
}
}
return $all_animals;
}