00 Votes

PHP: Add previous sub-array value to next sub-array value

Question by Guest | 2022-08-20 at 16:45

In each sub-array's end element, I want to add the previous sub-array's end-element.

$arr = [ [1,2,4], [4,2,6], [2,1,8] ];

How can I do that with for-iteration?

ReplyPositiveNegative
00 Votes

You mean something like that?

$arr = [ [1,2,4], [4,2,6], [2,1,8] ];

for ($i = 1; $i < count($arr); $i++) {
   $arr[$i-1][2] += $arr[$i][2];
}

// Result: [ [1,2,10], [4,2,14], [2,1,8] ]

Or should it be more flexible?
2022-08-20 at 22:57

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.