3

How can i reverse $str= "hello\n" to "olleh\n" without using any extra memory variable?

I looked up for prebuilt functions but they all use memory, also, i think string is immutable so basically can this be done without any tweak or creating a new string is the only option?

Arihant
  • 3,847
  • 16
  • 55
  • 86
  • 3
    Why would you need to do that? – Sean Bright Sep 27 '13 at 16:27
  • Is turning it into an array considered using extra memory? – Jon Lin Sep 27 '13 at 16:28
  • @JonLin Technically all strings are already an array so you wouldn't need to turn it into one. They are simply `char` arrays. – rfoo Sep 27 '13 at 16:29
  • 1
    @SeanBright It's a part of an example question given to me for a company recruitment, more than that i am inquisitive about whether something like this can be done or not – Arihant Sep 27 '13 at 16:29
  • Since PHP strings are immutable, it's impossible to do without creating a new string. If you reassign to the original variable, the old string will become garbage and its memory will be reclaimed immediately. – Barmar Sep 27 '13 at 16:29

3 Answers3

3

I don't think anything is immutable in PHP. So

$str = strrev($str);

may be of some use.

Fear the micro-optimization as it will take all your time, for no real result ! :)

Armage
  • 657
  • 8
  • 18
  • The variable is mutable, not the string itself. – Barmar Sep 27 '13 at 16:31
  • 1
    this will even reverse the '\n' which isn't how it's supposed to be right? – Arihant Sep 27 '13 at 16:32
  • @Barmar, ok, my bad. Thanks for the info. Arihant, no direct way to do that, you have to extract what you don't want to reverse and store it to reinject later... – Armage Sep 27 '13 at 16:35
3

I may be overlooking something, but if all your lines end in \n I think this might be the shortest method:

$str = strrev( trim( $str ) ) . "\n";

I'm not sure how much memory is involved though.

Jason
  • 1,987
  • 1
  • 14
  • 16
0

How much 'extra memory' you talking here? PHP has a neat function to flip strings for you : strrev()

Simply use

$str = strrev($string);

If you really wanted you could write a loop to do practically the same thing but that would use memory.

<?php
            $string = trim("Some Random string");
            // string length
            $len = strlen($string);
            // make string array
            $stringExp = str_split($string);
            // Loop through and print backwards
            for ($i = $len - 1; $i >= 0; $i--) {
                echo $stringExp[$i];
            }
            ?>
Darren
  • 13,050
  • 4
  • 41
  • 79