Sum of Array Elements in PHP
Let's find the sum of primitive elements in our array:
<?php
function func($arr) {
$sum = 0;
foreach ($arr as $elem) {
if (is_array($elem)) {
$sum += func($elem);
} else {
$sum += $elem;
}
}
return $sum;
}
var_dump(func([1, [2, 7, 8], [3, 4, [5, [6, 7]]]]));
?>
Given a multidimensional array of arbitrary nesting level, for example, like this:
<?php
$arr = [1, 2, 3, [4, 5, [6, 7]], [8, [9, 10]]];
?>
Using recursion, find the sum of the elements of this array.
Given a multidimensional array of arbitrary nesting level, containing strings inside, for example, like this:
<?php
$arr = ['a', ['b', 'c', 'd'], ['e', 'f', ['g', ['j', 'k']]]];
?>
Using recursion, merge the elements of this array into one string:
'abcdefgjk'