Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 368
Sk446 Avatar asked Jan 21 '11 15:01

Sk446


4 Answers

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
}
like image 100
helloandre Avatar answered Nov 10 '22 17:11

helloandre


Simple answer: don't use a foreach loop. Use a simple for loop instead:

for ($i = 0; $i < count($array); $i++) {
    if (isset($array[$i + 1])) {
        $thisValue = $array[$i]['value'];
        $nextValue = $array[$i + 1]['value'];

        $percentageDiff = ($nextValue-$thisValue)/$thisValue;
    }
}
like image 35
lonesomeday Avatar answered Nov 10 '22 16:11

lonesomeday


You should be able to use:

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

    $nextValue = next($array_copy);
    $nextValue = $nextValue['value'];

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

This copies the array and then moves the pointer along by 1.

like image 1
Matt Lowden Avatar answered Nov 10 '22 16:11

Matt Lowden


The easiest solution IMO is to change your mindset. Instead of inspecting the current and the next record, inspect the previous and the current record. Remembering the previous one is easier than getting the next one.

If you don't want that, you can also ditch the foreach and iterate C-style using for and a counter variable - one cavet though: PHP's sparse arrays can bite you, so you best call array_values() on the inspected array before iterating.

like image 1
tdammers Avatar answered Nov 10 '22 17:11

tdammers