[Solved] Button click counter [PHP]

I tried to create a variable to store a count of button clicked. Unfortunetlly i get this error:

 Undefined variable: counter

It’s my code:

    $counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
        echo $counter;

And it’s a form:

<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
    <input type = "submit" name = "button" value = "Submit" >
    <input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />

Anybody know what i’m doing wrong?

Solution #1:

There is no error in your code. Its working at my end. You need to check two points:

  1. PHP code should be above on HTML, HTML code will come after PHP code. So that $counter variable will be initialized.

  2. PHP and HTML code should be on same page.

As OP edited the question: So, the line $counter = isset($_POST['counter']) ? $_POST['counter'] : 0; should not be in if-block. To be sure, ** Make this line as a first line of PHP file. Then only $counter variable will be available for whole page.

Respondent: Adarsh Rajput

Solution #2:

Alternatively, if you want to save the counter, you can use sessions. Like this:


// if counter is not set, set to zero
if(!isset($_SESSION['counter'])) {
    $_SESSION['counter'] = 0;

// if button is pressed, increment counter
if(isset($_POST['button'])) {

// reset counter
if(isset($_POST['reset'])) {
    $_SESSION['counter'] = 0;


<form method="POST">
    <input type="hidden" name="counter" value="<?php echo $_SESSION['counter']; ?>" />
    <input type="submit" name="button" value="Counter" />
    <input type="submit" name="reset" value="Reset" />
    <br/><?php echo $_SESSION['counter']; ?>

By the way, your current code will show an Undefined index error because you are echoing $counter on your form but you haven’t initialized it yet. It will only exist, upon first form submission, not upon first normal load of the page.

Respondent: Kevin

Solution #3:

Variable is not defined because of this u get this error.

To hide this error write this in top of page error_reporting(0).

Check this..how to defined variable?

Respondent: Prashant Tapase

Solution #4:

you try to use a undelaired variable

<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />

this var doesn’t exists as the error says. guess you have a wrong setup of your code.

like the php is not on the same side or not above the html

Respondent: Dwza

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.