php

php: doing recursion with recursive iterator(iterator)s

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.

php to developers: “say ‘iterator’ five times fast”

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.

Continue reading →
Posted by grant horwood in php, 0 comments

php: write php 8.4’s array_find from scratch

there’s an rfc vote currently underway for a number of new array functions in php8.4 (thanks to symfony station for pointing this out!). the proposal is for four new functions for finding and evaluating arrays using callables. the functions are:

  • array_find()
  • array_find_key()
  • array_any()
  • array_all()

the full details can be read here

if we’re impatient, though, we can skip waiting for php8.4 and homeroll these ourselves.

Continue reading →
Posted by grant horwood in php, 0 comments