Search code examples
phpfunctionreturn

Function returns null (returned value is not null) in PHP


I have been scratching my head over a function for a while now and was wondering if anyone could see what I'm doing wrong? I'm trying to return a value from a function but it is null, even though I know that the value I return isn't. Here's my function:

if (!function_exists('findTopLevel')){
    function findTopLevel($id){
        $DatabaseID = $id;

        echo json_encode($DatabaseID); //correct
        $parentID = $_SESSION['items'][$DatabaseID]['ParentID'];
        echo json_encode($parentID); //correct

        if($parentID == "top"){
            echo json_encode($DatabaseID); //correct
            return $DatabaseID; //returns null
        }

        else if($parentID !== "top"){
            ini_set('memory_limit', '-1'); 
            findTopLevel($parentID);
        }
    }
}

I call it here:

if(!strpos($HiddenPositionArray, $DatabaseID)){

        $topLevel = findTopLevel($DatabaseID);
        echo json_encode($topLevel); //says: null
    }

(I will not echo all these stuff when I know it works.)

What's wrong?


Solution

  • I think you are missing the return statement in the recursion part. So calling findTopLevel calls findTopLevel again, which returns the correct value, but the first call doesn't return the value.

    function findTopLevel($id){
        $DatabaseID = $id;
    
        echo json_encode($DatabaseID);
        $parentID = $_SESSION['items'][$DatabaseID]['ParentID'];
        echo json_encode($parentID);
    
        if($parentID == "top") {
            echo json_encode($DatabaseID);
            return $DatabaseID;
        } else if($parentID !== "top") {
            ini_set('memory_limit', '-1'); 
            return findTopLevel($parentID); // The return here is important
        }
    }
    

    By the way, if you really need the function_exists part, you're doing something wrong.