Re: Reversing a string?
| From: | Kim Steinhaug | Date: | Thu, 13 May 2004 21:43:54 +0000 |
| Subject: | Re: Reversing a string? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-186162@lists.php.net to get a copy of this message | ||
Hehe, managed to do it on first try. This should do it :
<?php
$string = "hello world";
$length = strlen($string);
if($length>1){
$reversed = "";
for($i=0;$i<$length;$i++){
$reversed .= substr($string,$length-$i,1);
echo substr($string,$length-$i,1) . "<br>";
}
$reversed .= substr($string,0,1);
echo substr($string,0,1) . "<br>";
echo $reversed;
} else echo $string;
?>
I added some errochecking if the string is only 1 character, since there
should be no use in running the for loop then.
--
--
Kim Steinhaug
----------------------------------------------------------------------
There are 10 types of people when it comes to binary numbers:
those who understand them, and those who don't.
----------------------------------------------------------------------
www.steinhaug.com - www.easywebshop.no - www.webkitpro.com
----------------------------------------------------------------------
"Kristian Rasmussen" <kristian@amazing.as> wrote in message
news:20040513212741.83074.qmail@pb1.pair.com...
> Hi all,
>
> I need a script for reversing a string ("hello world" becomes "dlrow
> olleh"). I have tried the following:
>
> ---
> $length = strlen($i);
> $g = "";
>
> while ($length > 0)
> {
> $g = $i[$length] . $g;
> $length--;
> }
> echo $g;
> ---
>
> With, obviously, no success. Is this the way or could array_reverse()
> somehow be used?
>
> Kristian