In this tutorial, we will show you how to print a number in reverse order using PHP for loop and function.
How to Reverse Number in PHP?
Here are two ways:
- Reverse number program in PHP using loop
- Reserve a number with using the function in PHP
Reverse number program in PHP using loop
Let’s follow the below steps for creating a PHP program for reverse a number using loop and without using any function:-
- Declare a variable and assign number value, which you want to reverse
- Declare a new variable, which you store reverse number and initialize it with 0.
- iterate the number with loop
- Multiply the reverse number by 10, add the remainder which comes after dividing the number by 10 inside the loop.
- Print the reversed number
<?php //define a variable and assign value $num = 23456; //define variable and initialize with 0 $revNo = 0; // iterate with loop while ($num > 1) { // Multiply the reverse number by 10, add the remainder which comes after dividing the number by 10. $rem = $num % 10; $revNo = ($revNo * 10) + $rem; $num = ($num / 10); } //Print the reversed number echo "Reverse number of 23456 is: $revNo"; ?>
Source Code – reverse number program in php using loop
<!DOCTYPE html> <html lang="en"> <head> <title>Reverse number in PHP without using any function PHP </title> </head> <body> <h4>Reverse number in PHP without using any function PHP </h4> <?php //define a variable and assign value $num = 23456; //define variable and initialize with 0 $revNo = 0; // iterate with loop while ($num > 1) { // Multiply the reverse number by 10, add the remainder which comes after dividing the number by 10. $rem = $num % 10; $revNo = ($revNo * 10) + $rem; $num = ($num / 10); } //Print the reversed number echo "Reverse number of 23456 is: $revNo"; ?> </body> </html>
Reserve a number with using strrev() function in PHP
You can reverse a number In PHP using the inbuilt PHP function strrev(). Let’s follow the below steps for that.
- Declare a PHP variable and assign the number value to the variable
- Put a declare variable into inside the strrev() and print it
<?php $number = 123456; echo "Reverse string of $number is " .strrev( $number ); ?>
Source Code – Reserve a number with using the function in PHP
<!DOCTYPE html> <html lang="en"> <head> <title>Reverse number in PHP with using strrev() function PHP </title> </head> <body> <h4>Reverse number in PHP with using strrev() function PHP </h4> <?php $number = 123456; echo "Reverse number of $number is " .strrev( $number ); ?> </body> </html>
Conclusion
In this reverse number in PHP tutorial. You have learned how to reverse a number in PHP without using any function In PHP and also learn how to reverse a number using inbuilt PHP function strrev().