Search code examples
phparraysrecursionslicereverse

How to simulate array_reverse() using a recursive user-defined function?


I want to reverse the values in an indexed array using recursion. The output should be the same as array_reverse().

My code:

$array = [1,2,3,4,5,6,7];

function reverseString(&$s) {
    if(count($s) < 2){
        return;
    }
    $len = count($s);
    $temp = $s[0];
    $s[0] = $s[$len - 1];
    $s[$len - 1] = $temp;
    reverseString(array_slice($s, 1, $len - 2));
}

reverseString($array);
print_r($array);

returns:

Array (
    [0] => 7
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 1 )

array_slice() is a link of an array part, am I right?

Why aren't the inner elements being affected by my recursive swapping technique?


Solution

  • A string and an array are two separate things. I cleared up your algorithm a bit:

    <?php
    $array = [1,2,3,4,5,6,7];
    
    function reverseSequence(&$s) {
        $len = count($s);
        if($len < 2){
            return;
        }
    
        $rest = array_slice($s, 1, $len - 2);
        reverseSequence($rest);
        $s = array_merge([$s[$len - 1]], $rest, [$s[0]]);
    }
    
    reverseSequence($array);
    print_r($array);
    

    The output obviously is:

    Array
    (
        [0] => 7
        [1] => 6
        [2] => 5
        [3] => 4
        [4] => 3
        [5] => 2
        [6] => 1
    )