Home  >  Article  >  Backend Development  >  How to implement recursive summation of arrays in php

How to implement recursive summation of arrays in php

PHPz
PHPzOriginal
2023-04-18 09:47:04647browse

In PHP, an array is a common data structure that can be used to store multiple values. In some application scenarios, we need to sum a nested array. In this case, we need to use the recursive summation algorithm of the array.

The idea of ​​the recursive summation algorithm is to traverse each element in the array. If the element is an array, call itself recursively to calculate the sum of the array. Otherwise, add the value of the element to the sum.

The following is a PHP code that implements the recursive summation algorithm:

function array_sum_recursive($arr) {
    $sum = 0;
    foreach ($arr as $value) {
        if (is_array($value)) {
            $sum += array_sum_recursive($value);
        } else {
            $sum += $value;
        }
    }
    return $sum;
}

This function accepts an array as a parameter and returns the sum of all elements of the array. It first sets the sum to 0 and then iterates through each element in the array. For each element, it first checks if it is an array, and if so, it calls itself recursively to calculate the sum of this array, otherwise it adds the element's value to the sum. Finally return the sum.

Here are some examples of using this function:

$arr1 = array(1, 2, 3, 4, 5);
echo array_sum_recursive($arr1); // 输出 15

$arr2 = array(1, 2, array(3, 4, 5), 6, 7);
echo array_sum_recursive($arr2); // 输出 28

$arr3 = array(array(1, 2, 3), array(4, 5), array(6, 7, 8, 9));
echo array_sum_recursive($arr3); // 输出 45

As you can see, no matter how nested the arrays are, this function can correctly calculate their sum.

In practical applications, the recursive summation algorithm can be used in many scenarios, such as counting the number of nodes in a tree structure, calculating the sum of all values ​​in a multi-layer nested list, etc. Mastering the recursive summation algorithm can help us better handle these complex data structures and improve the efficiency and flexibility of the program.

The above is the detailed content of How to implement recursive summation of arrays in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn