Today we will learn how do we reverse number in order using PHP. We can use basic math method to calculate and you will learn how to use strrev() function in PHP or reverse order number. The sample example below will help you understand more and how we create algorithm to handle the task.
You will get the concept how to use the function strrev() in PHP. If you have a question about how to reverse numbers in PHP then I will give a simple example with a solution.
The process can seem complex, but using Basic Math The first method we will consider is the most basic method of reversing a number in PHP.
$org = 12345;
$reversed = 0;
while ($org > 0)
{
$reversed = ($reversed * 10) + ($org % 10);
$org = (int)($org / 10);
}
echo "Reversed number: $reversed";
We have initializing value original number and reverse number as zero.
The while loop will check the original number is still geater than zero then inside the loop we will find the last digit of original number, which is appeded to the reversed number variable.
The original number is starting divided by 10 and cast the result to integer value which will remove the decimal place value. The loop continusly handle the same process until the original has no digits left.
Output
Reversed number: 54321
Now we simply using built-in functions in PHP to reverse ordering number, firstly we will convert number to string using function strval() then reverse the string by using strrev() function. Let's see below example snippet how does it work.
$original_number = 12345;
// convert number to string
$string_number = strval($original_number);
// start reverse string
$reversed_string = strrev($string_number);
// typecasting string to integer
$reversed_number = (int) $reversed_string;
// display the result
echo "Reversed number: $reversed_number";
Just like I have comment on code above, the first we start convert the orginal number to string by using strval() function. After that using strrev() function to reverse value string. Then we start cast value string to integer back by typecasting (int).
So these two methods might help you to reverse number in pure PHP or even in Laravel or other PHP frameworks. The first method is abit have concept to understand basic math algorithm, but it is faster than the second method which we have to convert back and forth to fix the data type. For suggestion the second method is simpler and easier to understand as well as readable but in large scale number should not. Consider which one is the best for you. Have a nice day! thanks for reading this short article.
You might Also Like:
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him