How to increment letters like numbers in PHP?

How to increment letters like numbers in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

How to increment letters like numbers in PHP

Incrementing a string of characters follows the exact same logic as incrementing an integer, but without the built-in arithmetic operators we rely on for numbers. When you pass AAA and expect AAB, it looks simple. However, passing AAZ and expecting ABA introduces carry logic that requires manual iteration from the rightmost character to the left. If you simply increment the first character of a string like 'AAZ' in your head, you get B. But the computer sees this as a base-26 arithmetic problem where every position depends on the value of the one to its right.

To solve this, you must iterate through the string starting from the last character. You convert each character to its integer representation using ord(), increment that value, and then check if it has exceeded the upper bound of the alphabet ('Z'). If it has, you reset the current position to 'A' and carry over a +1 to the previous position. This loop continues until you either reach the start of the string or successfully increment without a carry.

Here is a robust function that implements this logic:

function incrementString(string $str): string {
    if (strlen($str) === 0) {
        return $str;
    }

    // Convert the string into an array of characters for mutability
    $chars = str_split($str);
    $carry = false;

    // Iterate backwards from the last character to the first
    for ($i = count($chars) - 1; $i >= 0; $i--) {
        // Get current ASCII value
        $currentChar = $chars[$i];
        
        // Calculate next character by adding 1 to ASCII code
        $nextChar = (ord($currentChar) + 1);
        
        // Check if we exceeded 'Z'
        if ($nextChar > ord('Z')) {
            // Reset to 'A' and set carry flag for the next position
            $chars[$i] = 'A';
            $carry = true;
        } else {
            // No carry needed, update character and stop processing
            $chars[$i] = (string)chr($nextChar);
            break; 
        }
    }

    // If we went through the whole string with a carry (e.g., ZZZ -> AAA),
    // we must prepend 'A' to maintain length consistency or expand it.
    // Based on standard counter behavior:
    if ($carry) {
        $chars = ['A'] + $chars;
    }

    return implode('', $chars);
}

The core of this solution lies in the conditional check inside the loop. When you increment 'Z', ord('Z') is 90. Adding 1 results in 91, which corresponds to [. Since we want to stay within the A-Z range, we detect this overflow. Instead of keeping the character as [, we reset it to 'A' and mark that the position to the left needs to be incremented.

This approach handles the transition from AAZ to ABA automatically because when the loop reaches the second 'A', it sees the carry flag set by the 'Z' below it, increments it to 'B', and breaks the loop since no further carry is needed.

Handling Edge Cases and Constraints

The most common pitfall in this type of logic is not handling the "all nines" scenario (in base 10 terms) or the "all Zs" scenario here. If your input is ZZZ, the loop will reset every character to A while carrying all the way to the left. Since there is no character to the left of the first 'Z' to increment, the carry persists after the loop finishes. In standard counter logic, this usually implies expanding the length of the string (e.g., ZZZ becomes AAAA). The code above handles this by prepending an 'A'.

You must also ensure your input validation is strict. This function assumes a pure uppercase alphabetic string. If you pass AAa or AA1, the ord() check against Z might behave unexpectedly if lowercase letters (which have higher ASCII values) are involved. Always sanitize input to ensure it contains only [A-Z].

Reusing Logic in Laravel

If you are building a larger application, specifically within the Laravel ecosystem, you might consider encapsulating this logic in a utility service or trait rather than scattering it across controllers. While there isn't a dedicated class in the core framework for string arithmetic, you can create a StringHelper facade or simply place this function in a App\Helpers\StringHelper.php file to keep your codebase clean.

For more complex scenarios where you need to handle mixed-case alphabets or specific base systems, look into third-party libraries, but for standard alphanumeric counters, the manual carry logic described here offers maximum control and zero dependencies.

Our network