Search code examples
phploopsforeachiteratorelement

Pull elements from next foreach item in PHP?


I'm doing a PHP 'traffic light' style warning system for my website, that basically says' if there is X percentage change between the current array entry and the next one, throw an error'.

So, I'm looping through my array elements in a foreach loop, however need to be able to do something like this: (note: this is just a basic example, but should be enough to get the idea)

foreach($array as $a)
{
$thisValue = $a['value'];
$nextValue = next($a['value']);

$percentageDiff = ($nextValue-$thisValue)/$thisValue;
}

I've put next() tags to get the next value but understand this only works for arrays. IS there something else I can use to get the next foreach item?

Thanks for your time!


Solution

  • do it the other way, and store the previous entry and compare those.

    $prev = null;
    foreach ($item as $i){
        if ($prev !== null){
            diff($prev, $i);
        }
        $prev = $i
    }