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

AlphaBay and Hansa dark web markets shut downPosted on Thursday July 20, 2017

The AlphaBay and Hansa marketplaces were known for trade in drugs, weapons and malware.

Kodi magazine 'directs readers to pirate content'Posted on Thursday July 20, 2017

The guide is being investigated by the Federation Against Copyright Theft.

Bitcoin swings as civil war loomsPosted on Thursday July 20, 2017

The Bitcoin community must agree how to tackle a slowdown in transaction times to avoid a schism.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


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

×