PHP String str_decrement() Function



The PHP String str_decrement () function is used to decrement an alphanumeric ASCII string. It accepts one parameter as an argument. This function works by reducing the value of the given string one step at a time.

The decrease of a string "B" to "A" and a numeric string "10" to "09" are two examples of this. It is particularly useful when working with sequential or incremental data.

The function will throw a ValueError if the string is empty, the input is not alphanumeric, or the string cannot be decremented (e.g., "A" or "0"). It only works with valid alphanumeric ASCII strings.

Syntax

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

string str_decrement ( string $string )

Parameters

This function accepts $string parameter which is the input string, which must be an alphanumeric ASCII string.

Return Value

The str_decrement() function returns the decremented 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.
  • The input string cannot be decremented (e.g., "A" or "0").

The str_decrement () function returns different values depending on whether or not the $option parameter is used. And FALSE on failure.

PHP Version

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

Example 1

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

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

Output

Here is the outcome of the following code −

A

Example 2

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

<?php
   $string = "10";
   echo str_decrement($string);
?> 

Output

This will generate the below output −

9

Example 3

Now the below code using the str_decrement() function and try to decrement a string that cannot be decremented.

<?php
   try {
      $string = "0";
      echo str_decrement($string);
   } catch (ValueError $e) {
      echo $e->getMessage();
   }
?> 

Output

This will create the below output −

str_decrement(): Argument #1 ($string) "0" is out of decrement range
php_function_reference.htm
Advertisements