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!




Get Free Tutorials by Email

About the Author

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

Today's Tech News

WannaCry ransom notice analysis suggests Chinese linkPosted on Monday May 29, 2017

Researchers say the WannaCry ransom note was poorly translated - possibly using Google Translate.

BA boss 'won't resign' over flight chaosPosted on Monday May 29, 2017

Chief executive Alex Cruz says flight disruption at Heathrow and Gatwick had nothing to do with cost cutting.

Hay Festival 2017: Stephen Fry's warning for the webPosted on Sunday May 28, 2017

Delivering a lecture at the Hay Festival, the actor said society could face "dire consequences".

Courtesy BBC News