Introduction
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.
Using the code
Assuming we want to remove all the elements containing "FirstValue" from an array, for example:
$value = "FirstValue";
And we have the following multidimensional array
:
$array["First"] = "FirstValue";
$array["Second"] = "SecondValue";
$array["Third"]["First"] = "FirstValue";
$array["Third"]["Second"] = "SecondValue";
$array["Fourth"]["Third"]["First"] = "FirstValue";
$array["Fourth"]["Third"]["Second"] = "SecondValue";
$array["Fifth"]["Fourth"]["Third"]["First"] = "FirstValue";
$array["Fifth"]["Fourth"]["Third"]["Second"] = "SecondValue";
Using a simple print_r($array)
on the above array, will print the following:
Array
(
[First] => FirstValue
[Second] => SecondValue
[Third] => Array
(
[First] => FirstValue
[Second] => SecondValue
)
[Fourth] => Array
(
[Third] => Array
(
[First] => FirstValue
[Second] => SecondValue
)
)
[Fifth] => Array
(
[Fourth] => Array
(
[Third] => Array
(
[First] => FirstValue
[Second] => SecondValue
)
)
)
)
In order to remove all the elements containing the value "FirstValue" from this multidimensional array,
we call the recursiveRemoval($array, $value)
function as follows:
recursiveRemoval($array, $value);
The recursiveRemoval
function code is as follows:
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 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]
).
Conclusion
I wrote this piece of code during work, to search and remove elements from a dynamically generated multidimensional array. Recursion can be a life saver in many cases,
hopefully my code will help you if you ever find yourself in the same situation as mine.