Array (
[0] => Array ( [0] => 4 [1] => 3 [2] => 5 [3] => 7 [4] => 210 )
[1] => Array ( [0] => 4 [1] => 9 [2] => 5 [3] => 7 [4] => 210 )
[2] => Array ( [0] => 4 [1] => 9 [2] => 25 [3] => 7 [4] => 210 ) )
I would like to replace the last entry of each array with the product of the values from its preceding elements. For example,
Array ( [0] => 4 [1] => 3 [2] => 5 [3] => 7 [4] => 210 )
Would actually be:
Array ( [0] => 4 [1] => 3 [2] => 5 [3] => 7 [4] => 420 )
How do I delete that last element and multiply the preceding elements and fill in the correct value as the last element?
I tried reading about array_splice()
, but do not understand the integer they used eg; array_splice($input, 1, -1);
2
Answers
A compact solution: array_walk() processes every row of the main array, the callable receives the sub-array as reference, removes the last element, calculates the product of all remaining elements using array_reduce() and assigns it as the last element of the sub-array.
Result:
As you iterate the rows, isolate all but the last element and multiply them. Overwrite the last element with that product. (Demo)
Or multiply everything, then divide by the popped-off element: (Demo)
Or remove the last element before multiplying (Demo)
Or enjoy arrow function syntax by uniting the product to the modified row: (Demo)
Or modify by reference using a classic loop: (Demo)