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>
>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>