How to reverse number in PHP without using function?

To reverse a number in PHP without using function declare a variable to store the reversed number, and initially assign zero to it. Now, extract the last digit from the original number, multiply the reverse number with 10, add the extracted digit to reversed number, and divide the original number by 10. Repeat this iteration until original number becomes zero.

You can use either loop for or while to do this exercise. Usually developers use while loop in such situations, where they don't know the number of iterations in advance.

Here you must make a note of the fact that there is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it towards zero, or the round() function provides finer control over rounding.

/* PHP program to reverse a number without using function */
 
$num = 2039;
$revnum = 0;
while ($num != 0)
{
	$revnum = $revnum * 10 + $num % 10;
	//below cast is essential to round remainder towards zero
	$num = (int)($num / 10); 
}
 
echo "Reverse number: $revnum\n";

Last Word

Hope you have enjoyed reading PHP program to reverse a number without using function. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.