-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?

0

1 Answer 1

4

+ is the arithmetic addition operator:

$news += $s[$i];

You want ., which is the string concatenation operator:

$news .= $s[$i];

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.