str_increment() is a built-in PHP function introduced in PHP 8.3.0that safely increments an alphanumeric ASCII string. Its behavior is identical in PHP 8.4 and PHP 8.5, but PHP 8.5 makes it essential by deprecating the old ++ operator on non-numeric strings.
Functionality
The function takes a string and returns the next logical value in sequence, handling carries automatically. It was created to replace the unpredictable and now-deprecated behavior of using the ++ increment operator on strings.
Basic Syntax:
str_increment(string $string): string
Rules & Examples
The function increments from right to left, and you can mix uppercase, lowercase, and numbers within the same string.
Example 1: Basic Increment.
<?php
$str = ABC ;
var_dump(str_increment($str));
// Output: string(3) "ABD"?>
Example 2: Handling Carries (Rollover).
<?php $str = DZ ; echo str_increment($str);
// Output: "EA" $str = ZZ ;
echo str_increment($str);
// Output: "AAA"
?>
Example 3: Mixed Character Types.
The "mode" of the leftmost character determines how the overflow is handled.
<?php
// Lowercase overflow (z -> a)
echo str_increment( zZ9 ); // Output: "aaA0"// Uppercase overflow (Z -> A)
echo str_increment( Z9z ); // Output: "AA0a"// Numeric overflow (9 -> 10)
echo str_increment( 9zZ ); // Output: “10aA”?>