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
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().
array_push()
array_pop()