Developing software in the Real World

Recursively deleting elements from an array

I had a need recently to delete items from a nested associative array and also any empty sub-arrays. My initial thought was to use array_walk_recursive, but this doesn’t work as you can’t unset nested elements and you only have access to the leaves. Clearly I needed a recursive function.

I’m sure that this has been done many times before, but this is my solution:

with this test:

This is very similar to how array_walk_recursive works except that I return the altered array rather than a boolean as it’s a recursive function.

The test shows how I use it:

If the callback returns true, then the element is deleted from the array, so for my case, I return true if the value is an empty array or null.

3 thoughts on “Recursively deleting elements from an array

Comments are closed.