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
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
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With