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

PHP_USER1
  • 628
  • 1
  • 14
  • 29

1 Answers1

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
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • **function($v) use (&$sum)** please can u explain me this step ? – PHP_USER1 Oct 10 '13 at 07:15
  • 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 – PHP_USER1 Oct 10 '13 at 07:31
  • Is there any way to do this without using **array_walk_recursive** – PHP_USER1 Oct 10 '13 at 08:28
  • 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. – Glavić Oct 10 '13 at 08:31
  • 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 – PHP_USER1 Oct 10 '13 at 08:56
  • I have updated answer; hope custom function `array_walk_recursive_rewrite` is what you are looking for. – Glavić Oct 10 '13 at 08:57
  • 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 – – PHP_USER1 Oct 10 '13 at 09:03
  • You cannot make this without recursion function for n-levels. For 6-levels code will look like [this](https://eval.in/53719), which is, again, **ridiculous**. **WHY** don't you wanna use functions? – Glavić Oct 10 '13 at 09:09