Search code examples
phpstringreverse

Reverse a string with php


I am trying to find a way to reverse a string, I've seen alternatives but i wanted to to it this way thinking outside the box and not using anyone else's code as an alternative, the code below reverses the string but I keep getting this error:

Notice: Undefined offset: 25 in C:\wamp\www\test\index.php on line 15

25 being the length of the string which is being deincremented.

//error_reporting(NULL);
$string = trim("This is a reversed string");

//find length of string including whitespace
$len =strlen($string);

//slipt sting into an array
$stringExp = str_split($string);

//deincriment string and echo out in reverse
for ($i = $len; $i >=0;$i--)
{
echo $stringExp[$i];
}

thanks in advance


Solution

  • As others said, there's strrev() to do this.

    If you want to build it on your own (for learning?): your problem is that you're starting with your index one too high - a string of length 25 is indexed from 0 to 24, so your loop has to look like this:

    for ($i = $len - 1; $i >=0;$i--)
    {
       echo $stringExp[$i];
    }