0

Consider:

<?php
class hitung
{
    function hitungBiaya($arr, $totalBiaya)
    {
        $totalBiaya += $arr[0]['biaya'];
        array_splice($arr, 0);
        if ($arr !== null && count($arr) > 0) {
            $this->hitungBiaya($arr, $totalBiaya);
        }
        return $totalBiaya;
    }
}

$hitung = new hitung;

$data = [
    [
        "biaya" => 100,
    ], [
        "biaya" => 1000
    ],
    [
        "biaya" => 5000
    ],
    [
        "biaya" => 3000
    ]
];

$jumlah = $hitung->hitungBiaya($data, 0);
echo $jumlah;
?>

How can I fix this?

I expected to get 8100, but when I run this function, it only gives me 100 as a result.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124

1 Answers1

0

Code is in the C language as shown below.

Based on an old mathematical formula:

Sum of n numbers = sum of (n-1) numbers + nth term

Please adjust for array index, overshooting or it being less than 0.

int sum(int arr[], int arrlength)
{
    if (arrlength == 0)
        return 0;

    return (sum(arr, arrlength - 1) + arr [arrlength]);
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124