luca.p.alexandru
luca.p.alexandru

Reputation: 1750

Function not working as expected in PHP

What is wrong with the output of this function, it prints out INF int the browser where as I expected it to print out 654321 The exact same function written in C# print out the expected result.

<?php
        function reverse($n, $r){
            if($n == 0) {
                return $r;
            }
            return reverse($n/10, $r*10 + $n%10);
        }

        echo reverse(123456, 0);
?>

Upvotes: 0

Views: 91

Answers (2)

Liam Allan
Liam Allan

Reputation: 1115

Try the strrev() function:

strrev('123456'); //654321

Upvotes: 2

baldrs
baldrs

Reputation: 2161

It does not do integer division. In C# you deal with strict typing, and when you divide 25 by 4 in C# you will get integer result, 6. In php you will get 6.25, float result.

Try intval your results before recursion to get integer division

Upvotes: 1

Related Questions