Searching and removing a value from a multidimensional array in php

Recently I found myself in a situation where I needed to search and remove a value from a dynamically generated multidimensional array with a different size and length.

After many trials and errors I found that the best solution is to recursively loop through the array and locate and remove the value.

So I wrote the following function, that takes two parameters, first is the array passed by reference and the second is the value we want to completely remove from the array:

function recursiveRemoval(&$array, $val)
{
if(is_array($array))
{
foreach($array as $key=>&$arrayElement)
{
if(is_array($arrayElement))
{
recursiveRemoval($arrayElement, $val);
}
else
{
if($arrayElement == $val)
{
unset($array[$key]);
}
}
}
}
}

First thing we’re doing is checking if the array passed to the function is actually an array.
If the array passed is an array, we iterate through its elements,
If the element is also an array (our array is not a one dimensional array), we recursively call the function recursiveRemoval($arrayElement, $val) again to break the multidimensional array into one dimensional arrays.
At the end, we process the one dimensional array elements, and we compare them to the passed value we want to remove, and we unset the key of the array ($array[$key]).

To download a fully working example, please go to:
http://www.codeproject.com/KB/PHP/RecursivelyRemoveArrayVal.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *