-1

What's the problem for the following code:

function rString($s) {
     $news = "";
     for ($i = strlen($s); $i >= 0; $i--) {
         $news += $s[$i];
     }
     return $news;
}
echo rString("happy birthday");

It returns 0 which is unexpected, I thought "" will be an empty string, and for every iteration the last character of a string should append to the $news (that is, to reverse a string). But it seems like "" is not accepted in php?

user3783243
  • 5,368
  • 5
  • 22
  • 41

1 Answers1

4

+ is the arithmetic addition operator:

$news += $s[$i];

You want ., which is the string concatenation operator:

$news .= $s[$i];

Or... just use strrev()...

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98