recursion has a bad reputation amongst programmers; it’s convoluted and complicated and difficult to debug, a real footgun. it’s something you do at school (if you went to school for that sort of thing) and then never touch again if you can avoid it. which is a drag, because there’s a lot of use cases for recursion. data structures of arbitrary depth are everywhere: file systems, dom trees, that 32kb json packet your integration partner just shovelled into your api.
in this post we’re going to over two features of php that help make recursion easier: the RecursiveIterator
interface, which provides us with methods and features that make writing recursive functions easier, and the dreadfully-named RecursiveIteratorIterator
class which we can use to flatten down arbitrarily-deep data structures.
we’ll be building a recursive function using RecursiveArrayIterator
, starting with a simple loop and working up to the full function. then we’ll look at how leverage RecursiveIteratorIterator
to smash that nested array into a single level so we can extract data, either with a simple loop or a more-complex-but-powerful call to iterator_apply
.