How to Increment by 1 to all the Digits of a given Integer in PHP ?
Last Updated :
11 Mar, 2024
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
Using String Conversion
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
$number = 110102;
echo "Original Number: $number \n" ;
$len = strlen ((string) $number );
$add = str_repeat ( "1" , $len );
$str_num = (int) $add ;
$result = $number + $str_num ;
echo "Incremented Number: $result" ;
?>
|
Output
Original Number: 110102
Incremented Number: 221213
Using Arithmetic Operations
Take an integer with value 1. Then we will perform arithmetic operations on it to get an integer of only 1s which will be of same length as that or original integer. Then, finally we will add this integer to original integer to get the desired result.
Example: Illustration of incrementing by 1 to all the digits of a given integer in PHP using arithmetic operations.
PHP
<?php
$number = 1920;
echo "Original Number: $number \n" ;
$len = strlen ((string) $number );
$add = 1;
for ( $i = 0; $i < $len ; $i ++) {
$number = $number + $add ;
$add = $add * 10;
}
echo "Incremented Number: $number" ;
?>
|
Output
Original Number: 1920
Incremented Number: 3031
Using Array Manipulation
Create an array with value of all elements equals to 1. Then, merge all elements of array together into a string and then convert this string into a number. Finally, add this number to the original given integer to get the result.
Example: Illustration of incrementing by 1 to all the digits of a given integer in PHP using array manipulation method.
PHP
<?php
$number = 2024;
echo "Original Number: $number \n" ;
$num_arr = str_split ( strval ( $number ));
$len = count ( $num_arr );
$ones_arr = array_fill (0, $len , 1);
$str_num = (int) implode( "" , $ones_arr );
$result = $number + $str_num ;
echo "Incremented Number: $result" ;
?>
|
Output
Original Number: 2024
Incremented Number: 3135
Share your thoughts in the comments
Please Login to comment...