Reverse a Number in PHP with Program
This blog explains about Reverse a Number in PHP with Program . They are explained very well below :
Today, we will learn how to Reverse a Number in PHP with Program .
First consider the number 1234.
Here we need to get last number first.
Hence i am using the modulus operator with divisor value as 10 for getting the remainder value to move from last into first place.
Shall we go through the program to reverse a number in PHP now?
A string can be reversed either using strrev() function or simple PHP code.
For example, on reversing JAVATPOINT it will become TNIOPTAVAJ.
- Assign the string to a variable.
- Calculate length of the string.
- Declare variable to hold reverse string.
- Run for loop.
- Concatenate string inside for loop.
- Display reversed string
- Take (input or assign) a number
- Assign 0 to the variable, in which we are going to store reverse number (Here, I am using ‘reverse’)
- Run the following two steps until number is not zero
- Get the digit using modules (%) operator and add it into the ‘reverse*10’
- Now, divide the number by 10Finally, when number will be zero, print the ‘reverse’
Swapping two numbers
Two numbers can be swapped or interchanged. It means first number will become second and second number will become first.
- a = 20, b = 30
- After swapping,
- a = 30, b = 20
There are two methods for swapping:
- By using third variable.
- Without using third variable.
I . Swapping Using Third Variable
II . Swapping Without using Third Variable
Swap two numbers without using a third variable can be done in two ways:
- Using arithmetic operation + and ?
- Using arithmetic operation * and /
Program: Reverse a Number in PHP
$m = 1234; $r=0;
for($i=0; $i<3; $i++)
$m = $m/10;