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

Bees 'go online' in ManchesterPosted on Friday September 22, 2017

Rory visits a beekeeper in Manchester who is gluing wireless chips to his bees.

The long wait for a Persian iPhone keyboardPosted on Friday September 22, 2017

The new Apple's iOS has Persian keyboard. BBC Persian's Sam Farzaneh discusses why it is an important feature.

Uber London loses licence to operatePosted on Friday September 22, 2017

Ride-hailing app Uber is "not fit and proper" to operate in London, the transport regulator says.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×