How to use Arithmetic Operations In PHP

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
   
// Declaring the number
$number = 1920;
echo "Original Number: $number \n";
 
// Number of digits in the number
$len = strlen((string) $number);
// Declaring another variable with value 1
$add = 1;
 
for ($i = 0; $i < $len; $i++) {
   
    // Adding variable $add and $number
    $number = $number + $add;
   
    // Multiplying the value of $add with 10
    $add = $add * 10;
}
// Printing the result
echo "Incremented Number: $number";
?>


Output

Original Number: 1920 
Incremented Number: 3031

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

Similar Reads

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....

Using Arithmetic Operations

...

Using Array Manipulation

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....

Contact Us