Reverse string without strrev

前端 未结 23 1009
忘了有多久
忘了有多久 2020-12-13 13:19

Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.

My first solution was something like this:

23条回答
  •  再見小時候
    2020-12-13 14:23

    you could use substr with negative start.

    Theory & Explanation

    you can start with for loop with counter from 1 to length of string, and call substr inside iteration with counter * -1 (which will convert the counter into negative value) and length of 1.

    So for the first time counter would be 1 and by multiplying with -1 will turn it to -1

    Hence substr('abcdefg', -1, 1); will get you g
    and next iteration substr('abcdefg', -2, 1); will get you f
    and                       substr('abcdefg', -3, 1); will get you e
    and so on ...

    Code

    $str = 'abcdefghijklmnopqrstuvwxyz';
    for($i=1; $i <= strlen($str); $i++) {
        echo substr($str, $i*-1, 1);
    }
    

    In Action: https://eval.in/583208

提交回复
热议问题