Ac0*_*Ac0 0 php arrays foreach
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>
Run Code Online (Sandbox Code Playgroud)
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!
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>";
}
Run Code Online (Sandbox Code Playgroud)