-1

I have recursive method in PHP merging values of array.

If array has more than 2 elements it sum up first two values to first one and removes second value. It does again and again until is only 1 value. Whole sum of these operations is result of function. However I get nesting error for that method:

PHP Fatal error: Uncaught Error: Maximum function nesting level of '256' reached, aborting

I think that problem lies in removing second element of array. It seems that it doesn't remove it properly.

function mergeList($A)
{
    $arraySize = count($A);
    if ($arraySize < 2) {
        return 0;
    } else {
        $A[0] = $A[0] + $A[1];
        unset($A[1]);
        return $A[0] + mergeList($A);
    }
}

Example of method:

$A = [1, 2, 3, 4];

Output should be 19, because [1,2,3,4] -> [3,3,4] -> [4,6] -> [10]

Sum of operations 3 -> 6 -> 10 = 19

Jsowa
  • 9,104
  • 5
  • 56
  • 60
  • Are you assigned to recursion excersise? `$A = array_sum($A)` – Banzay Apr 06 '20 at 09:48
  • That is not solution because this is part of my code and I transformed it to easiest example. I can't use array_sum in this case. – Jsowa Apr 06 '20 at 10:32

1 Answers1

3

You need to call array_values() every time you unset any array element before pass reduced array to recursion. Otherwise there is no $A[1] and the recursion loops erroring with Notice: Undefined offset: 1

function mergeList($A) {
    $arraySize = count($A);
    if ($arraySize < 2) {
        return $A[0];
    } else {
        $A[0] += $A[1];
        unset($A[1]);
        $A = array_values($A);
        return mergeList($A);
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Banzay
  • 9,310
  • 2
  • 27
  • 46