I try not to get overly technical in this space, but when I get a chance to implement one of my very favorite programming techniques, I have a hard time keeping it to myself.  I want to tell you about recursion.  Per wikipedia:

A common method of simplification is to divide a problem into subproblems of the same type […] where problems are solved by solving smaller and smaller instances.

Here’s the example.  Earlier this week I was dealing with a problem where I needed to turn the english words “true” and “false” into the boolean values true and false.  This would be easy enough to do if it were simply one instance of the words:

That’s easy enough.  But what if the words were in an array?

A little more work, but still not too bad.  But what if I didn’t know ahead of time if the words were in an array?  What if I didn’t know how deeply nested they were into the array?  The answer is recursion.

Notice anything weird there? Notice that I have the function calling itself. In case you don’t know, that’s pretty weird. That’s a bit like having your phone call itself. The end result is that it’s going to keep breaking down deeper and deeper into the original variable, until all the true/false words are boolean.

Dear lord, who cares?

It’s a fair question. The real point here is that there was a simpler way to do this that probably could have worked. I could have done some combination of the first two techniques, crossed my fingers that I’d never encounter a deeper array, and moved on the something else. Why make something bulletproof? Why make something overkill? Because I can. And because the next time I need it, when maybe it’s not overkill but it’s the only way to get by, it will be easy.

Update: Since posting this, LexBlog’s own Angelo Carosio pointed out to me that I could also have used php’s excellent array_walk_recursive().