0
    <?php
    $r1=array("n"=>3,"ni"=>2,["nis"=>3,[["nish"=>4],[["nishi"=>"n"],[["nishi"=>true]]]]]);
    echo "<pre>";
    //print_r($r1);
    echo "</pre>";
    $sum=0;

    for ($i=0;$i<count($r1);$i++) {
    $curr=$r1[$i];
    if (is_array($curr)) {
                $sum += array_sum($curr);
            } else if (is_numeric($curr)) {
                $sum += $curr;
            }
            echo $sum;
    }
?>

i am trying to find the the sum of the values in the array and leave the string . if anyone knows the answer plz help

3
  • I am not getting the desired result ie 12 Commented Oct 10, 2013 at 7:06
  • so plz help , I am new to array ....i have little knowledge in array and how the recursion work Commented Oct 10, 2013 at 7:07
  • 1
    @vaibhavmande: because you have PHP<5.4.x Commented Oct 10, 2013 at 7:07

1 Answer 1

1

Use array_walk_recursive to walk over each element of the array:

$sum = 0;
array_walk_recursive($r1, function($v) use (&$sum) {
    if (is_numeric($v)) $sum += $v;
});
var_dump($sum); # 12

Edit: Use without array_walk_recursive function:

function array_walk_recursive_rewrite(array $data) {
    $sum = 0;
    foreach ($data as $v) {
        if (is_array($v)) {
            $sum += array_walk_recursive_rewrite($v);
        } elseif (is_integer($v)) {
            $sum += $v;
        }
    }
    return $sum;
}
var_dump( array_walk_recursive_rewrite($r1) ); # 12
Sign up to request clarification or add additional context in comments.

8 Comments

function($v) use (&$sum) please can u explain me this step ?
is it possible to use the whole code without this function($v) use (&$sum) . instead of this can v use anything else coz i have never used this
Is there any way to do this without using array_walk_recursive
There is, make custom function, that does exactly what array_walk_recursive does. But why? Reason that you haven't used this before is just ridiculous.
no no this is not the reason , i want to try without function ......you can see my 1st attempt .......I m trying with for loop .......but thanks for the info about array_walk_recursive
|

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.