0

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);
?>
asked Sep 4, 2013 at 9:27
2
  • 9
    Well, PHP is not C#. If you want to reverse a string (or a number) just use the built-in strrev. Commented Sep 4, 2013 at 9:29
  • 1
    try reverse((int)($n/10), $r*10 + ($n%10)); Commented Sep 4, 2013 at 9:29

2 Answers 2

2

Try the strrev() function:

strrev('123456'); //654321
h2ooooooo
39.6k8 gold badges70 silver badges108 bronze badges
answered Sep 4, 2013 at 9:29
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Sep 4, 2013 at 9:31

2 Comments

Thank you,this is the answer is expected
@juice then please click on the tick mark symbol visible below the voting symbol of this answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.