0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
e.klara.k
  • 369
  • 1
  • 6
  • 17

1 Answers1

5

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Philipp
  • 15,377
  • 4
  • 35
  • 52
  • I'll speculate that the `function_exists` is to protect against repeat `includes`, the solution being `include_once`. – Flosculus Oct 16 '15 at 09:04
  • Thank you so much, that did the trick! Exactly, @Flosculus. However include_once will not work for this specific file since it needs to run several times. I may transfer my functions to another document later on. – e.klara.k Oct 16 '15 at 09:11