php - Numeric array: add value of previous element to current element -
For each element in the array, I have to add the value of the current element. Example:
Hey ([0] = & gt; 460 [1] => 25 [2] => 25 [3] => 25 [4] => 25 [5 ] = & Gt; 25 [6] => 25) How can I get the following:
Array ([0 ] = & Gt; 460 [1] => 485 [2] => 510 [3] = 535 [4] = 560 [5] => 585 [6] = > 610) Any thoughts?
This is a quick solution compared to the rest:
foreach ($ A as $ i = & gt; $ val) {// Make sure the current item is not the first / / because if there is a base number first ($ i & gt; 0) {// update is running $ i ( Index) // adding the previous value ($ a [$ i-1]) with the current value $ Val) $ a [$ i] = $ a [$ i - 1] + $ val; }} As 0 is the first value, we can not increase before that) therefore if Statement And here's a demo:
This does not matter if looping method you use How do you implement it? Look, here's exactly the exact same thing done for for loop >
($ i = 0; $ i & lt; counts ($ a); $ i ++) is. {If ($ i & gt; 0) {$ a [$ i] = $ a [$ i - 1] + $ one [$ i]; }} It all comes down to the coder's preference.
The correct data for those two ends comes back: Array ([0] => 460 [1] => 485 [ 2] => 510 [3] => 535 [4] = 560 [5] = 585 [6] => 610)
Comments
Post a Comment