angelesguerra Posted November 4, 2020 Share Posted November 4, 2020 I am new at php. I am trying to loop a number in each click of a button. See attached picture for reference. 1 should iterate after the click of the button and will stop to iterate when it gets to 5. Here is my code: <!DOCTYPE html> <html> <body> <div>Question <?php $num = 5; $n = 1; $n <= $num; echo $n; ?> of <?php echo $num;?></div> <form method="post"> <button id="button" class="button" value="add" name="add">Click</button> </form> </body> </html> If I try to loop it this way, <!DOCTYPE html> <html> <body> <div>Question <?php $num = 5; for($i = 1; $i <= $num; $i++){ echo $i; } ?> of <?php echo $num;?></div> <form method="post"> <button id="button" class="button" value="add" name="add">Click</button> </form> </body> </html> the result is Question 12345 of 5. Quote Link to comment https://forums.phpfreaks.com/topic/311676-how-to-loop-or-iterate-variable-in-every-click-of-button/ Share on other sites More sharing options...
gw1500se Posted November 4, 2020 Share Posted November 4, 2020 PHP is stateless which means it does not remember what happened previously. To do what you want you will need to keep track of the variables using sessions. It would not be a loop at all. You would need to check and increment a $_SESSION variable on each call. Quote Link to comment https://forums.phpfreaks.com/topic/311676-how-to-loop-or-iterate-variable-in-every-click-of-button/#findComment-1582229 Share on other sites More sharing options...
angelesguerra Posted November 4, 2020 Author Share Posted November 4, 2020 @gw1500se can you show me an example for this? thank you so much Quote Link to comment https://forums.phpfreaks.com/topic/311676-how-to-loop-or-iterate-variable-in-every-click-of-button/#findComment-1582230 Share on other sites More sharing options...
gw1500se Posted November 4, 2020 Share Posted November 4, 2020 The link points to the documentation which has examples. You can also search for hundreds of examples. Just make sure you understand the documentation first. Quote Link to comment https://forums.phpfreaks.com/topic/311676-how-to-loop-or-iterate-variable-in-every-click-of-button/#findComment-1582231 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.