Exercise: Array Reverse

Exercise 20 Very easy

Prerequisites for the exercise

  1. PHP Arrays — Basics

Objective

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

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.

View Solution

New file

Inside the directory you created for this course on PHP, create a new folder called Exercise-20-Array-Reverse and put the .php solution files for this exercise within it.

Solution

Reversing an array is a pretty elementary idea. We only ought to swap corresponding elements in the array. That is, the first element is to be swapped with the last element; the second element with the second-last element; and so on and so forth.

This has to continue until all but the middle element has been swapped, if there is any. This is because there is no point of swapping the middle element, since its swap would be with itself.

So altogether this means that if we have an array of 4 elements, we'll need to apply the swapping routine only on the first two elements (which will automatically encompass the last two elements as well).

Similarly, if we have an array of 5 elements, once again the first two elements will need to be swapped (with the last two ones). The third element (which is the middle element) will be swapped with itself and so likewise we won't need to swap it.

In our implementation of reverse(), it's quite apparent that we need a for loop to iterate up to, but excluding, the middle element. In each iteration, we swap the current element with the corresponding element from the right-hand side of the array.

Moreover, because we need to modify the original array, it's paramount to mark the $arr parameter in reverse() as a reference parameter which gets arguments passed by reference.

Now for this entire logic, we need essentially three helper variables:

  1. $temp — meant to temporarily hold the current element of the array while it is swapped with the corresponding element.
  2. $n — meant to hold the length of the array which will ultimately be used in accessing the corresponding ith element from the right-hand side of the array (i.e. in the expression $n - $i - 1 below).
  3. $mid — meant to cache the index right before which we need to end the given loop.

Starting at $i = 0, we iterate over each of the given array's elements up to the index $mid, meanwhile making the desired swaps. And this simply reverses the whole list.

Altogether, we get to the following code:

<?php

function reverse(&$arr) {
   $n = count($arr);
   $mid = (int) ($n / 2);

   for ($i = 0; $i < $mid; $i++) {
      $temp = $arr[$i];
      $arr[$i] = $arr[$n - $i - 1];
      $arr[$n - $i - 1] = $temp;
   }

   return $arr;
}

If we want to, we can even squeeze in the declarations of $n and $mid inside the for loop's header, while also formatting the code for better readability, as shown below:

<?php

function reverse(&$arr) {
   for (
      $i = 0, $n = count($arr), $mid = (int) ($n / 2);
      $i < $mid;
      $i++
   ) {
      $temp = $arr[$i];
      $arr[$i] = $arr[$n - $i - 1];
      $arr[$n - $i - 1] = $temp;
   }

   return $arr;
}

This makes sense here since both $n and $mid are supposed to be used exclusively inside the loop only, hence we put them inside the loop's header.

And this completes this exercise.