phploopsfor-loopcyclecontrol-structure

PHP Auto Increment a (float) column from another column data


My program starts like this:

START  |   B    |  S      |  P       |
4000   | 215.05 | 4182.72 |  182.72  |

where:

B = Buy
S = Sell
and
P = Profit.

I'm calculating the values this way:

bv = 18.60; //fixed value
sv = 19.45; //fixed value
START = 4000; //fixed value 
B = (START/bv);
S = (B*sv);
P = (S-START);

How can I manage to store the "SELL" value inside "START" as a loop and recieve a table like this:

START  |   B    |  S      |  P       |
4000   | 215.05 | 4182.72 |  182.72  |
4182.72| 224.87 | 4373.72 |  191.00  |

??

I tried:

$start= 4000;
//$inic = $cashinic;
$bv= 18.6; //buy value
$sv= 19.45;//sell value

$buy= ($start/$bv);
$sell = ($comp*$sv);
$profit = ($sell-$start);

for($i = 1; $i<=100; $i++)
{
?>
  <tr>
    <td><div align="center"><?php echo $start; ?> </div></td>
    <td><?php echo $buy; ?></td>
    <td><?php echo $sell; ?></td>
    <td><div align="center"><?php echo $profit; ?> </div></td>
   </tr>
<?php
}
?>
</table>

but it only gives me this results:

START  |   B    |  S      |  P       |
4000   | 215.05 | 4182.72 |  182.72  |
4000   | 215.05 | 4182.72 |  182.72  |
4000   | 215.05 | 4182.72 |  182.72  |
....   | ...... | ....... |  ......  |

and so on... I'd really appreciate your help.

Do I need another column which will be the auto increment one? Something like this:

Col_index |START  |   B    |  S      |  P       |
      1   | 4000  | 215.05 | 4182.72 |  182.72  |
      2   |  ...  |  ...   |   ...   |   ...    |

P.D. I'm not using a database, is it necessary? (mostly because I don't think I need a database)


Solution

  • You need to update $start at the end of the loop so the next iteration uses the new value:

    $start = 4000;
    $bv = 18.6;
    $sv = 19.45;
    
    for($i = 1; $i <= 100; $i += 1) {
        $buy = $start / $bv;
        $sell = $buy * $sv; // I replaced $comp with $buy is that correct?
        $profit = $sell - $start;
        echo $start . "\t" . $buy . "\t" . $sell . "\t" . $profit . "\n";
    
        // update start
        $start = $sell;
    }
    

    Output:

    4000    215.05376344086 4182.7956989247 182.79569892473
    4182.7956989247 224.8814891895  4373.9449647358 191.14926581108
    4373.9449647358 235.15833143741 4573.8295464576 199.8845817218
    4573.8295464576 245.90481432568 4782.8486386344 209.01909217683
    ...
    

    If you don't like to increment $start (you might get rounding errors) you can also set $start to the value of row-$i by using a bit of clever math:

    $start = 4000;
    $bv = 18.6;
    $sv = 19.45;
    
    for($i = 0; $i < 100; $i += 1) { // loop needs to start at 0
        $s = $start * pow($sv / $bv, $i);
        $buy = $s / $bv;
        $sell = $buy * $sv;
        $profit = $sell - $start;
        echo $s . "\t" . $buy . "\t" . $sell . "\t" . $profit . "\n";
    }