Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String str_increment() Function



The PHP String str_increment () function is used to increment an alphanumeric ASCII string. It modifies the given string by incrementing its characters, just like a counter, with special consideration for both numeric and alphabetic sequences.

The str_increment() function allows developers to efficiently handle complex string increment operations which makes it an important part of PHP's string manipulation features.

Syntax

Below is the syntax of the PHP String str_increment () function −

string str_increment ( string $string )

Parameters

This function accepts $string parameter which is the input string.

Return Value

The str_increment() function returns the incremented alphanumeric ASCII string. A ValueError is thrown in the following cases:

  • The input string is empty.
  • The input string is not an alphanumeric ASCII string.

PHP Version

The str_increment () function is available from PHP 8.3.0 onwards.

Example 1

Here is the basic example of the PHP String str_increment () function to increment the given alphanumeric ASCII string.

<?php
   $string = "B";
   echo str_increment($string); 
?>

Output

Here is the outcome of the following code −

C

Example 2

In the below PHP code we will use the str_increment () function and see how it works when a mixed string is given with a number.

<?php
   // Define the string here
   $string = "a1";
   $result = str_increment($string);

   // Display the result
   echo "Incremented String: $result\n";
?> 

Output

This will generate the below output −

Incremented String: a2

Example 3

Now the below code using the str_increment() function and try to handle overflow for example z will become aa.

<?php
   // Define the string here
   $string = "z9";
   $result = str_increment($string);

   // Display the result
   echo "Incremented String with Overflow: $result\n";
?> 

Output

This will create the below output −

Incremented String with Overflow: aa0

Example 4

In the following example, we are using the getinfo() function for incrementing a string in a for loop.

<?php
   // Define the string here
   $string = "a9";
   echo "Original String: $string\n";

   for ($i = 1; $i <= 5; $i++) {
      $string = str_increment($string);
      echo "Increment $i: $string\n";
   }

?> 

Output

Following is the output of the above code −

Original String: a9
Increment 1: b0
Increment 2: b1
Increment 3: b2
Increment 4: b3
Increment 5: b4
php_function_reference.htm
Advertisements