Question: I have this function that I wrote that is abysmally slow since php does not handle recursion well. I am trying to convert it to a while loop, but am having trouble wrapping my head around how to do it.

Can anyone give me some tips?

```
    public function findRoute($curLoc, $distanceSoFar, $expectedValue) {

    $this->locationsVisited[$curLoc] = true;
    $expectedValue += $this->locationsArray[$curLoc]*$distanceSoFar;

    $at_end = true;
    for($i = 1; $i < $this->numLocations; $i++) {
        if($this->locationsVisited[$i] == false) {
            $at_end = false;

            if($expectedValue < $this->bestEV)
                $this->findRoute($i, $distanceSoFar + $this->distanceArray[$curLoc][$i], $expectedValue);
        }
    }

    $this->locationsVisited[$curLoc] = false;

    if($at_end) {
        if($expectedValue < $this->bestEV) {
            $this->bestEV = $expectedValue;
        }
    }
}

```

Answer: 
I'm not going to convert your code, but you can convert a recusive function into an iterative one by creating a stack:

```
$stack= array();

```

And instead of invoking `$this->findroute()`, push your parameters onto this stack:

```
$stack[] = array($i, $distanceSoFar + $this->distanceArray[$curLoc][$i], $expectedValue);

```

Now surround basically everything in your function into a while loop draining the stack after having primed it:

```
while ($stack) { 
    // Do stuff you already do in your function here

```
You can convert a recursive function into an iterative function by using a stack to store the current state. Look into `array_push()` and `array_pop()`.