PHP function to increment variable by 1 each time

PHP function to increment variable by 1 each time

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP Function to Increment Variable by 1 Each Time

You are trying to generate unique button names like yes1, no1, yes2, and so on, based on how many times a function is called within a specific session. The core logic you need is simply incrementing a counter. In standard procedural PHP, this is straightforward: declare a variable outside the loop or conditional block, increment it when necessary, and use that value in your string interpolation.

However, looking at the code snippet provided, there are fundamental architectural issues preventing this from working as intended. The primary obstacle isn't the incrementing mechanism itself, but rather how you are handling state between form submissions and how PHP processes HTML forms.

Managing State Across Form Submissions

In the example code, the script initializes $number to 0 inside the repeat() function:

function repeat() {
    $number = 0; // This resets every time the function is called!
    $number++; 
    // ...
}

Because this variable is local to the function and reset on every call, it will always be 1. To get sequential numbers like 2, 3, or 4, you must store that count in a persistent location. For a simple game state without a database, the $_SESSION superglobal is the standard solution.

You should move the counter into the session at the very beginning of your script:

session_start();
if (!isset($_SESSION['step'])) {
    $_SESSION['step'] = 0;
} else {
    $_SESSION['step']++;
}
$current_step = $_SESSION['step'];

By checking isset and incrementing the session variable, you ensure that if a user clicks "Yes" on step 1, the next request sees step 2. This approach decouples the counter from the function scope and ties it to the user's browser.

The Trap of Dynamic Form Names

Your specific goal is to create inputs with names like yes1 and no1. In PHP, you can access these via $_POST['yes1']. While this works for simple scripts, relying on dynamic POST keys as string literals in a switch statement (e.g., case yes1:) is syntactically incorrect. Case labels must be string literals or constants; they cannot be variables.

To handle dynamic names correctly, you need to use the switch statement with the actual variable holding the name:

$buttonName = $_POST['yes'.$current_step] ?? $_POST['no'.$current_step];

switch ($buttonName) {
    case 'yes' . $current_step:
        // Handle yes answer for current step
        break;
    case 'no' . $current_step:
        // Handle no answer for current step
        break;
}

This pattern constructs the case label dynamically. It is robust and scalable regardless of how many questions you have in the array.

A Better Pattern: Associative Arrays

While fixing the increment logic solves your immediate problem, relying on string-based names for form inputs often leads to fragile code. As the game grows, managing arrays of buttons where keys are strings like yes1, no2, etc., becomes difficult to read and debug.

A more maintainable approach is to use associative arrays or a dedicated state object. Instead of generating unique input names, you can map the step number directly to an action key:

$actionKey = 'step_' . $current_step;
// In your form:
<input type="submit" name="action" value="Yes" data-step="yes">
<input type="submit" name="action" value="No" data-step="no">

Then, in your processing logic:

$action = $_POST['action'];
$stepData = $_SESSION['game_state'][$current_step]; 

if ($action === 'yes' && $stepData['id'] == $current_step) {
    // Proceed to next question
}

This shifts the complexity from HTML attribute names to a clean data structure. It is significantly easier to refactor later if you decide to add "Maybe" or "Skip" buttons, or if you need to pass additional metadata about the creature type alongside the answer.

Conclusion on Implementation

To summarize the fix: move your counter into $_SESSION so it persists across requests, and use string concatenation within your switch statements to match dynamic input names. If you anticipate scaling this application further, consider refactoring toward associative arrays or a state machine pattern to avoid managing string-based keys manually.

Our network