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

Robotic barman pours Rory a pintPosted on Friday March 24, 2017

The BBC’s technology correspondent Rory Cellan-Jones gets a beer poured for him by a robotic barman - but how long does it take?

Row over US ISP customer data salesPosted on Friday March 24, 2017

US politicians have voted to let ISPs gather and sell data about what Americans do online.

Ofcom plans instant payback for broadband woesPosted on Friday March 24, 2017

Customers who suffer poor service could get automatic payouts under Ofcom's plan.

Courtesy BBC News