Objective

Create a function to reverse a given array, in-place.

Difficulty

Very easy

Description

Consider the following array of numbers:

<?php

$nums = [1, 5, 9];

If we reverse this array, the order of elements will simply get reversed.

That is, the first element will become the last element; the second element will become the second-last element; the third element will become the third-last element; and so on and so forth.

In this exercise, you have to create a function reverse() that reverse a given array.

PHP does provide us with a built-in array_reverse() function to accomplish the exact same thing as we're trying to do in this exercise, but it doesn't necessarily explain how reversal might happen internally.

Here's the signature of the function you're supposed to implement:

<?php

function reverse($arr) {
   // Your code here.
}

The given parameter $arr is the array to reverse.

Note that the function must mutate the array in-place, i.e. the original array must be modified. Moreover, the function must also return the modified array.

Below shown is an illustration of the usage of the function:

<?php

function reverse(...) { ... }
            
$nums = [1, 5, 9];

print_r(reverse($nums));
print_r($nums);
Array ( [0] => 9 [1] => 5 [2] => 1 ) Array ( [0] => 9 [1] => 5 [2] => 1 )

As can be seen here, the call to reverse() returns the reversed array [9, 5, 1], and the actual array $nums is also modified, as is confirmed by the second print_r()'s output.