Search code examples
phploopsvariableswhile-loopsubtraction

Subtract previous variable from current variable (or itself if first iteration) while looping


I need to subtract the value from the previous iteration from the current iteration's value. On the first iteration, there will be no previous value, so the result should be zero.

For example (expected value)

expected output

and my code was as below:

$sel = mysql_query("SELECT RIGHT(serial,4) as value, serial, date 
    from photodata 
    where folder='$m' or (serial >= '$cm' && serial <= '$cm2')") or die(mysql_error());

while ($selt=mysql_fetch_array($sel)) {
    $value = $selt['value'];
    $ser = $selt['serial'];
    $dd = $selt['date'];
    $rr = $value-$value;  
}

I'm really sure $rr won't work, but I just tried.


Solution

  • Just print $rr as subtract value and check, changed some code in above snippet. Hope, it will help you out.

    $index = 0;
    $oldv = 0;
    while ($selt=mysql_fetch_array($sel)) {
        $value = $selt['value'];
        $ser = $selt['serial'];
        $dd = $selt['date']; 
        if($index==0) {
            $oldv = $value;
            $index = 1;
         }
        $rr = $value - $oldv;
        echo $rr;
        $oldv = $value;
     }