You have some issues in your code, for example this
if ($result = term_exists($term, $taxonomy)) {
should probably be
if ($result == term_exists($term, $taxonomy)) {
there are several of this same type of error in the code that you’ve posted.
This is usually why some people code like this
if (term_exists($term, $taxonomy) == $result) {
because the above would create an error if you use ‘=’ instead of ‘==’ rather than fail quietly.