PHP to rotate an array right


Code Solution:

<?php
function rotateArrayRight($array, $steps = 1)
{
    if ($steps === 0 || count($array) === 0) {
        return $array;
    }

    $steps %= count($array);
    $rotatedPortion = array_splice($array, -1 * $steps);
    $array = array_merge($rotatedPortion, $array);
    return $array;
}

$originalArray = [1, 2, 3, 4, 5];
$rotatedArray = rotateArrayRight($originalArray, 2);

print_r($rotatedArray); // Output: [4, 5, 1, 2, 3]

Explanation:

1. Input Validation:

The function verifies if the provided $steps are 0 or the array is empty. If so, there’s no need for rotation, and the original array is returned.

2. Adjust Steps:

The $steps value is adjusted to be within the bounds of the array. The modulo operator (%) ensures that the steps wrap around correctly.

3. Split and Rotate:

The portion of the array to be rotated is split using array_splice(). This portion is stored in $rotatedPortion.

4. Merge and Return:

The $rotatedPortion is merged back into the original array using array_merge(). The resulting array is then returned.

Implementation:

To use the function, simply provide an array as the first argument and the number of steps to rotate (optional) as the second argument. The function will return the rotated array.

Time Complexity:

The time complexity of this solution is O(n), where n is the number of elements in the array. This is because it performs a single pass through the array to split and merge the rotated portion.

Advantages:

  • Efficient and easy to implement.
  • Handles edge cases, such as empty arrays or zero steps.
  • Allows for arbitrary rotation distances.