Sunday, May 01, 2016

Multi dimensional array manipulation in php

This week I wrote some code that got the following reaction of a fellow coder; when we need to change this code it will be a hell for us to understand.

The code looked like this, but with even more loops and manipulations.

The fun starts on line 17 where i begin with the nested loops. I know that looks ugly from the start. At the time I couldn't think of another way to handle this.

PHP has a lot of array functions, but most functions only handle one dimensional arrays. There are a few functions that can handle multi dimensional arrays by using recursion but they come with their limititations.

Array_walk_recursive applies a callback on each element of the array. But the problem is that any key that holds an array will not be passed to the function. When you want to manipulate arrays that is a bit of a problem.

Array_merge_recursive is out of the picture because it doesn't manipulates arrays. If the arrays you want to merge have the same numeric key the second array value will be appended.

Array_replace_recursive is the function that shows the most promise, if it wasn't for a separate code to build the replacement array.

That is why I have decided to create an array manipulater that works with callbacks based on the depth of the array and/or array key.
I have written it as a drupal module you can find here

The code from before will look as follows:

The benefit of this class is that the nesting of arrays is kept to a minimum, and that the manipulation of the array you want is contained to the array itself. In the code above I needed to use the full array keys to know if there where manipulations (lines 25 and 42).

The class still has some warts in the form of needing to force a key for a certain depth and nested field keys in a complex array, but i'm going to fix that in future versions.

Update

I have updated the class after a tip from the same developer who made the first remark.