I have written a function that works really well for what it is intended, but I just realized that it will need to make calls to itself, and wondered if that is able to be done (first), whether is is a smart thing to do (second), and are there any potential pitfalls (third).

It is a function that places new members positions and then checks to see if the placement caused another member to cycle. When it does cause a cycle, then it automatically creates additional (re-entry) positions, but then it has to check to see if another cycle has been created, which is likely...

So I would need to call the function from within itself, and this could happen multiple times, as the membership position base expands, because the number of consecutive cycles doubles with each successive level.

I hope this makes sense, and it is probably unnecessary to explain all of this to just get the simple question answered, that is if it is in fact a simple question...

So, any help, suggestions, discouragements, etc.?

Looking forward to a speedy response from someone with the right answer, because I am at a point of needing to make this work, now...

Douglas:?:

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by showman13

1. Yes.
2. Maybe, depending on your implementation.
3. When not handled correctly, or a lot of deep calls, it can cause a stack overflow.

If you are absolutely sure a recursive function is the only way, just do it. Remember that there is most likely a non-recursive solution too.

It's called an iterator. You can do it, but there has to be an escape mechanism - there must be a point where the iterator breaks, otherwise you'll get an infinite loop. Smart? Depends on the implementation and how robust the system is. php has a number of in-built iterators (see SPL). You also need to consider memory and storage issues. Massive loops could cause timeout problems, etc.

Anyhow, I'm no expert. Just a few things that hit me over the years.

//EDIT
Sorry Pritaeas - simultaneous post - "recursive" was the term I was looking for.

Edited by diafol: n/a