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!
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
}
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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With