Introduction

Greetings! Welcome to our lesson today, where we'll unravel a fascinating aspect of array manipulation. Here's the question: How would you traverse an array not from the beginning to the end, or vice versa, but from the center outward in either direction? Today's lesson is all about exploring this concept with PHP. Brace yourself for a captivating learning journey.

Task Statement

Our task is to produce a new array, given an array of integers, that starts from the center of the original array and alternates direction towards both ends. That is, the first element of our new array will be the middle element of the original one.

After defining the starting point, we will alternate between elements to the left and to the right of this center until all elements have been included. If the length of the initial array is even, we first take the element to the left of the center, then the one to the right of the center, and then do the alternation as described above.

For example, for numbers = [1, 2, 3, 4, 5], the output would be [3, 2, 4, 1, 5].

We will break down this seemingly complex task into manageable pieces to progressively build our PHP solution. Keep in mind an additional condition: the length of the array — represented as n — can range from 1 to 100,000, inclusive.

Solution Building: Step 1

First, let's establish the midpoint of our array. Our task requires us to expand our array from the center to the ends, so we divide its length by 2 using integer division in PHP. If we find that the array's length is odd, we include the middle element in the newOrder array, given it has no counterpart. If the array's length is even, newOrder initially remains empty.

Here is how it looks in PHP:

PHP
<?php
function iterateMiddleToEnd($numbers) {
    $mid = intdiv(count($numbers), 2);  // Calculate the midpoint
    $newOrder = [];  // Array to store new order

    if (count($numbers) % 2 == 1) {
        $newOrder[] = $numbers[$mid];  // Adding middle element to resulting array if length is odd
    }
    // newOrder remains empty for now if length is even
    
    return $newOrder;
}
?>
Solution Building: Step 2
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal