Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 892
Steven Mcsorley Avatar asked Nov 29 '22 14:11

Steven Mcsorley


2 Answers

You're trying much too hard, always consult the manual and/or a search engine to check if there are native functions to do what you want before you end up "reinventing the wheel":

strrev — Reverse a string

http://php.net/manual/en/function.strrev.php

$string = "This is a reversed string";
echo strrev($string);
// Output: gnirts desrever a si sihT
like image 95
Wesley Murch Avatar answered Dec 10 '22 23:12

Wesley Murch


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];
}
like image 36
oezi Avatar answered Dec 10 '22 22:12

oezi