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.

10
  • It must be if($arr==0) { . You don't have $array defined anywhere , so why use it ? This solves just the syntactical problem issue.. Commented Apr 19, 2014 at 6:32
  • i just edited and the problem still persists.. Commented Apr 19, 2014 at 6:33
  • What do you think if ($arr==0) means? Commented Apr 19, 2014 at 6:34
  • First of all, you are not at all calling your function. Commented Apr 19, 2014 at 6:35
  • @Hanky웃Panky i mean if array is 0 ..ie null Commented Apr 19, 2014 at 6:35

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

1

Use array_sum($array) PHP function

2 Comments

yes i know ..and i did it to learn about recrusion method in php
@user3550798 - factorial is good example to learn recursive method :)
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.

3 Comments

so in the line "$total += sum_array($element);" the whole array elements are added to $total ...right ?
The whole inner-array. In my expanded example, that would be the [5, 2]
@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]).
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

4 Comments

Just a note: You don't need to call array_sum() again. See this answer.
@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. ;)
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.
@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.
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

1 Comment

While this code snippet may solve the question, including an explanation 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.