Why does PHP return INF (infinity) for the following piece of code:
<?php
$n = 1234;
$m = 0;
while ($n > 0)
{
$m = ($m * 10) + ($n % 10);
$n = $n / 10;
}
var_dump($m);
?>
The expected result was 4321, but PHP returned INF, float type:
float INF
I wrote the same code in Python and C# and got the expected output – 4321
Python
n = 1234
m = 0
while (n > 0):
m = (m * 10) + (n % 10)
n = n / 10
print m
C#
static void Main(string[] args)
{
int n = 1234;
int m = 0;
while (n > 0)
{
m = (m * 10) + (n % 10);
n = n / 10;
}
Console.WriteLine(m);
Console.ReadLine();
}
In php
$n / 10will return a float number, not integer.So
$n > 0will always betrue.Change
while($n > 0)to
while($n > 1)orwhile((int)$n > 0), then you will get the right result.