The array_walk_recursive can be a very handy built-in function for PHP as it can traverse any size of array recursively and apply a callback function. Whether we want to find whether an element is in a multidimensional array or not, or get the total sum of the array of the multidimensional array, we can use this function without any problem.
The following code sample will produce an output of 136 when executed:
function array_sum_recursive(Array $array) {
$sum = 0;
array_walk_recursive($array, function($v) use (&$sum) {
$sum += $v;
});
return $sum;
}
$arr =
[1, 2, 3, 4, 5, [6, 7, [8, 9, 10, [11, 12, 13, [14, 15, 16]]]]];
echo array_sum_recursive($arr);
The other two built-in recursive array functions in PHP are array_merge_recursive and array_replace_recursive. We can use them to merge multiple arrays...