Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to subtract from a starting amount?

I am a beginner at coding and I am printing a number (36 here) and I have 4 buttons. Pressing each button should subtract from the amount remaining. So when I press the ‘3’ button, the amount remaining is 33 but after this when I press the button ‘4’, the value displayed should be 29, but what I get is 32 instead.

How do I make it so the value of variable mleft is not reset to 36 each time I press a button?

<div class="bt_grp">
    <form method="post">
        <button value=1 name="pressed">1</button>
        <button value=2 name="pressed">2</button>
        <button value=3 name="pressed">3</button>
        <button value=4 name="pressed">4</button>
    </form>
</div>
<?php 
$mleft = 36;
if (isset($_POST['pressed'])) {
    echo $_POST['pressed'];
    $mleft = $mleft -= $_POST['pressed'] ;
    
}
?>

<div class="flex-container">
    <div id="matchn">
        <h3>Matchsticks left</h3>
        <h1><?=$mleft?></h1>
    </div>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Each time you post the form, you set $mleft to 36 before you subtract from it.

If you want the value to persist between calls, use a session variable and subtract from that.

<?php
session_start();
?>

<div class="bt_grp">
    <form method="post">
        <button value=1 name="pressed">1</button>
        <button value=2 name="pressed">2</button>
        <button value=3 name="pressed">3</button>
        <button value=4 name="pressed">4</button>
    </form>
</div>
<?php 
$mleft = $_SESSION['mleft'] ?? 36;
if (isset($_POST['pressed'])) {
    echo $_POST['pressed'];
    $mleft -= $_POST['pressed'] ;
}
$_SESSION['mleft'] = $mleft;
?>

<div class="flex-container">
    <div id="matchn">
        <h3>Matchsticks left</h3>
        <h1><?=$mleft?></h1>
    </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading