Reputation: 51
I'm trying to figure out how to make an array add the value of the previous array, so far, looking at the PHP manual I got how to add a single value for each position of the array, but I don't understand how can I add the previous value to the actual value. That's what i got checking the manual:
<!DOCTYPE html>
<head>
</head>
<body>
<?php
foreach (array(422, 322, -52323, 7452) as &$val) {
$val = $val + 2;
echo "$val<br>";
}
?>
</body>
I know that I have to change the "+ 2" with "add previous value" but don't know how I can tell it to do that, tried to add "$val[0]" or "$val[$i]" but not doing what I think it does.
Thank you!
Upvotes: 0
Views: 1148
Reputation: 163287
You are directly iterating over an array, and in that case you don't need the reference to &$val
, you can just use $val
If you don't want to store the array in a variable, you could also "remember" the previous value of the iteration (which will also work in case the keys are not numerical for example)
$previous = null;
foreach (array(422, 322, -52323, 7452) as $val) {
if ($previous) {
$previous += $val;
} else {
$previous = $val;
}
echo $previous . PHP_EOL;
}
Output
422
744
-51579
-44127
See a Php demo.
Upvotes: 0
Reputation: 11318
You've complicated matters by putting the array directly into foreach
. To get the previous value, you need to have access to the array itself.
Once you have that, you can get the index of the current value with foreach
, which you can use to determine the index of the previous value:
$array = array(422, 322, -52323, 7452);
foreach ($array as $index => &$val) {
// the first index is 0, in that case there is no previous value
// (trying to access $array[$index - 1] ($array[-1]) will fail then)
if ($index > 0) {
$val = $val + $array[$index - 1];
}
echo "$val<br>";
}
Upvotes: 5