Skip to content
Advertisement

PHP looping through a function before returning value

I have simplified this. I have this line of code in a method in a (codeigniter framework) controller:

$the_result = $this->loop1($ordered_bookings);

And this is is the ‘loop1’ function:

public function loop1($ob, $count=1):array {
    ++$count;
    if($count < 5)
    {
        $this->loop1($ob, $count);
    }
    else
    {
        return array(1, 2, 3);
    }
}

What I need to be able to do is loop through loop1 function until certain conditions are met before then returning the results array. Problem is calling the function again at the end of loop1 seems to be returning to the original call, and returning nothing at that (obviously I guess).

If I change the loop1 function to simply this:

public function loop1($ob):array {
    return array(1, 2, 3);
}

It works perfectly.

I haven’t done this sort of PHP work for a long time and the need to declare a returnType itself was new to me. How can I achieve what I’m aiming for here?

Advertisement

Answer

Your function returns the array only when $count it reaches 5. However, when it finally returns the array, you do nothing with it. That is why it gives you nothing. If you want to do something with the array, you need to capture it when you call loop1 inside itself and pass it along with a return like so:

public function loop1($ob, $count=1):array {
    ++$count;
    if($count < 5)
    {
        return $this->loop1($ob, $count);
    }
    else
    {
        return array(1, 2, 3);
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement