1

Am a php developer and i have studied about recursive function and i coded to find the sum of elements in an array with recursive function but i got the error.

THE CODE WHICH I GOT FROM INTERNET

$example = array(10,20,30);


function sum_array($array) {


$total = 0;
foreach ($array as $element) {
    if(is_array($element)) {
        $total += sum_array($element);
    } else {
        $total += $element;
    }
}
return $total;


}

echo sum_array($example); // Outputs 60

MY CODE

<?php
 $example = array(10,20,30);

function add_me($arr) {

  if($arr==0) {

    return $arr;



 } 
  return add_me($arr[0]+$arr[1]+$arr[2]);



}

The first code which i found from the internet works well but in case of my code it gives an error. When i called it using echo add_me($example); it forms an error .

Can you please tell me why it is like that ..Any help would be appreciated ..Thanks.

L_7337
  • 2,650
  • 28
  • 42

5 Answers5

2

If you're trying to create a recursive function, use the following:

function sum_array($array)
{
    $sum = 0;
    foreach ($array as $value) {
        // if the value itself is an array
        // recurse further: call the function again
        if (is_array($value)) {
            $sum = $sum + sum_array($value);
        }
        // if the value is not an array,
        // simply add it to $sum
        else {
            $sum = $sum + $value;
        }
    }
    return $sum;
}

echo sum_array([3, 4, [5,6], 8]); // => 26

is_array() checks if the value is an array and if so, call the function again. If the value is not an array, the value is simply added to $sum. At the end, $sum is returned.


This can be done in multiple ways. Here are some:

Using array_walk_recursive():

function sum_array($array) {
    $sum = 0;
    array_walk_recursive($array, function($v) use (&$sum) {
        $sum += $v;
    });
    return $sum;
}

echo sum_array([3, 4, [5,6], 8]); // => 26

Using array_reduce():

function callback($v, $w) {
    return $v + (is_array($w) ? array_reduce($w, __FUNCTION__) : $w);
}

echo array_reduce([3, 4, [5,6], 8], 'callback'); // => 26
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

Use array_sum($array) PHP function

PravinS
  • 2,640
  • 3
  • 21
  • 25
1

Since I can't really do anything with your code to make it functional, I figured I'd explain the function you got from the internet:

//Set sample data
$example = array(10,20,30);
function sum_array($array) {
    //first time called, we start at 0
    $total = 0;
    //Loop through each value in the array
    foreach ($array as $element) {
        //If the value is another array, we use recursion
        if(is_array($element)) {
            //using the recursion, we send the array to this function and add to total
            $total += sum_array($element);
        } else {
            //value was not an array, but scalar, add to total
            $total += $element;
        }
    } // Go to next value
    //Give the total back to asker
    return $total;
}
echo sum_array($example); // Outputs 60

That's the same code you had with comments added for each line. For an example of how it works with the $example array, it would go:

sum_array([10,20,30])
$total = 0
$element = 10
$total += 10  //10
$element = 20
$total += 20 //30
$element = 30
$total += 30 //60

return $total //60

With the example data, no recursion happens at all, it would if you had an array as one of the values, ie [10, [5, 2], 20] and then it would go like:

sum_array([10,[5,2],20])
$total = 0
$element = 10
$total += 10  //10
$element = [5, 2]
sum_array([5,2])
    $total_1 = 0
    $element_1 = 5
    $total_1 += 5 //5
    $element_1 = 2
    $total_1 += 2  //7
    return $total_1 //7
$total += $total_1 //17
$element = 20
$total += 20 //37
return $total //37

Hopefully that will help aid you in understanding recursion.

Jon
  • 4,746
  • 2
  • 24
  • 37
  • so in the line "$total += sum_array($element);" the whole array elements are added to $total ...right ? – user3550798 Apr 19 '14 at 07:06
  • The whole inner-array. In my expanded example, that would be the `[5, 2]` – Jon Apr 19 '14 at 07:07
  • @user3550798: `$foo += $bar` is a shorter way of writing `$foo = $foo + $bar`. In this case, it means `$total = $total + sum_array($element)` (where `$element` is `[5, 2]`). – Amal Murali Apr 19 '14 at 07:08
0

If you are looking for recursion on arrays, you could use RecursiveArrayIterator class , also see RecursiveIteratorIterator class

A simple illustration (taken from this answer):

<?php
$a = array(1,2,array(3,4, array(5,6,7), 8), 9);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
    $new_arr[] = $v;
}
echo array_sum($new_arr); // "prints" 45
Community
  • 1
  • 1
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Just a note: You don't need to call `array_sum()` again. See [this answer](http://stackoverflow.com/a/3778104/1438393). – Amal Murali Apr 19 '14 at 06:49
  • @AmalMurali, Come on I know that. The `$a` array is actually flattened to `$new_arr` so that the OP can use it for other purposes too. ;) – Shankar Narayana Damodaran Apr 19 '14 at 06:53
  • I'm sure you know that. But I thought the OP wasn't really familiar with recursion, so that was more of an FYI comment. – Amal Murali Apr 19 '14 at 06:59
  • @AmalMurali, I _intentionally_ did that , since after sometime OP may come and ask how to add the first four elements , last four elements , third and seventh element.. as such. So putting it inside an array would be more easier. Also, since OP is familiar with `array_sum()` , I used that. – Shankar Narayana Damodaran Apr 19 '14 at 07:03
0
function sum(array $input) {
    #Base case
    if ( count($input) == 0 ) {
        return;
    }

    if ( is_array( $input[0] ) ) {
        return $input[0][0] + sum( array_merge_recursive( array_slice($input, 1), array_slice($input[0], 1) ) );
    }
    else {
        return $input[0] + sum( array_slice( $input, 1) );    
    }
}

print sum([10, 20, 30]); //60

print sum([10, [10,10], [20,10]]); //60
slier
  • 6,511
  • 6
  • 36
  • 55
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. - [From review](https://stackoverflow.com/review/low-quality-posts/15066593) – Ferrybig Feb 01 '17 at 09:14