This post is part of a series on Code Challenges.

This code challenge was to reverse an array, both with and without the use of a new array variable. While PHP does have the array_reverse function, this is the result without resorting to the standard library.

View Version #1 on Repl.it.
View Version #2 on Repl.it.


Version 1

This was the version I settled on after thinking around Version 2.

<?php

$items = ['R', 'E', 'V', 'E', 'R', 'S', 'E'];
$expected = ['E', 'S', 'R', 'E', 'V', 'E', 'R'];

$iterations = count($items) - 1;

for ($x = 1; $x <= $iterations; $x++) {
  $items[] = array_splice($items, $iterations - $x, 1)[0];
}

if ($expected === $items) {
  echo 'Success!';
} else {
  echo 'Failed.';
}

Version 2

This was what I first thought of when I was challenged to solve the issue, but it didn’t seem “right” to me.

<?php

$items = ['R', 'E', 'V', 'E', 'R', 'S', 'E'];
$expected = ['E', 'S', 'R', 'E', 'V', 'E', 'R'];

$right = count($items) - 1;
$iterations = (int)count($items) / 2;

for ($left = 0; $left < $iterations; $left++) {
  $leftTemp = $items[$left];

  $items[$left] = $items[$right];
  $items[$right] = $leftTemp;
  --$right;
}

if ($expected === $items) {
  echo 'Success!';
} else {
  echo 'Failed.';
}

Tagged in: