How to use String Conversion In PHP
Generate a string which will be of the same length as the input integer and will contain only 1’s in it. Then we will convert this string into an integer. Then, finally add this integer to the original integer to get the desired result.
Example: Illustration of incrementing by 1 to all the digits of a given integer in PHP using string conversion method.
PHP
<?php // Declaring the number $number = 110102; echo "Original Number: $number \n" ; // Number of digits in the number $len = strlen ((string) $number ); // Generating the addition string $add = str_repeat ( "1" , $len ); // Converting it to an integer $str_num = (int) $add ; // Adding them and displaying the result $result = $number + $str_num ; // Print the result echo "Incremented Number: $result" ; ?> |
Original Number: 110102 Incremented Number: 221213
How to Increment by 1 to all the Digits of a given Integer in PHP ?
In PHP, incrementing all digits of an integer by 1 involves breaking the number into individual digits, adding 1 to each, and reconstructing the integer. This can be accomplished through array manipulation, arithmetic operations, or string conversion methods. Suppose, if the given number is 123 then the desired output is 234.
Examples:
Input: 12345
Output: 23456
Input: 110102
Output: 221213
Table of Content
- Using String Conversion
- Using Arithmetic Operations
- Using Array Manipulation