How to reverse a number in PHP. In this tutorial, you are going to learn how to write a code to reverse a number in php without using function (in-built functions).
There are multiple approaches you can use to solve this problem. PHP doesn’t provide any in-built function to reverse a number directly.
Check whether a number is prime or not
Reverse a Number in PHP without using Function
In this example, we write a PHP code to reverse a number without using function. We write a logic which take number as an argument and reverse that number.
METHOD 1– Reverse a number without using any inbuilt functions.
Let’s create a simple function which takes a number as an input and return the reverse of a number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* Return reverse of a number. @param int number */ function reverse_number($number){ $sum = 0; while( floor($number) ) { $newnum = $number % 10; $sum = $sum * 10 + $newnum; $number = $number/10; } return $sum; } echo reverse_number(5674); /* Output - 4765 */ |
METHOD 2 – PHP program to Reverse a number using in-built functions.
In this approach, we use a little trick to reverse a number. As PHP doesn’t provide any inbuilt function for reversing a number directly.
a) Using str_split() and array_reverse()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/* Return reverse of a number. @param int number */ function reverse_number($number){ /* Convert them into an array. */ $arr = str_split($number); /* Reverse the array. */ $rev_arr = array_reverse($arr); /* Implode them. */ $rev = implode("",$rev_arr); return $rev; } echo reverse_number(5674); |
Top five most used PHP functions for beginners
b) Using strrev() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function reverse_number($number){ /* Typecast the number into string. */ $snum = (string) $number; /* Reverse the string. */ $revstr = strrev($snum); /* Typecast string into int. */ $reverse = (int) $revstr; return $reverse; } echo reverse_number(5674); |
Conclusion
I demonstrated three approaches to reverse a number in PHP. If you know some other method then please let us know through your comments.