Search code examples
phpfunctionnested-loops

Recursive PHP function is not returning a result


Here is my function:

function loop($id) {

    unset($result, $sql, $query);
    $sql = " SELECT parent_id FROM page_entries WHERE id = '$id' ";
    $query = mysql_query($sql) or die(mysql_error());
    $result = mysql_fetch_assoc($query) or die(mysql_error());

    if ($result['parent_id'] != 0) {
        echo $result['parent_id'] . "... looping<br>";
        loop($result['parent_id']);
    } else {
        echo $result['parent_id'] . "... done loop";
        return $result['parent_id'];
    }
}

echo loop('2');

I'm echoing the parent_id for testing. This is what is output to the browser:

1... looping

0... done loop

Where I'm not sure: the echo loop('2') doesn't echo anything from return $result['id'] if I comment out the echo lines in the function. I've tried testing by changing the return to return 'foo'; and still nothing.

How can I fix it?


Solution

  • At a glance, I think

    loop($result['parent_id']);
    

    should be

    return loop($result['parent_id']);
    

    otherwise your if branch is returning nothing.