What is the best approach to summing up values in a multidimensional array in PHP?
To sum up values in a multidimensional array in PHP, you can use a recursive function that iterates through each element of the array and adds up the values. This approach allows you to handle arrays of any depth and size.
function sumMultiArray($arr) {
$sum = 0;
foreach ($arr as $value) {
if (is_array($value)) {
$sum += sumMultiArray($value);
} else {
$sum += $value;
}
}
return $sum;
}
$multiArray = [[1, 2], [3, [4, 5]]];
$totalSum = sumMultiArray($multiArray);
echo $totalSum; // Output: 15
Keywords
Related Questions
- How can PHP be optimized for better performance when handling frame emulation tasks?
- In PHP, what is the recommended approach for displaying the next image after a question has been answered in a quiz format?
- What are some best practices for handling group bookings and comparisons in a PHP booking system?