PHP Program for Array Left Rotation by d Positions
Given an array, the task is to rotate an array to the left by d position in PHP. Array left rotation by d positions involves shifting array elements to the left by d positions.
Examples:
Input: arr = {1, 2, 3, 4, 5, 6, 7}, d = 2
Output: 3 4 5 6 7 1 2
Input: arr = {3, 4, 5, 6, 7, 1, 2}, d = 2
Output: 5 6 7 1 2 3 4
Using Array Slice() Function
In this approach, first, we will slice the array into two parts - one from index d to the end, and the other from the start to index d-1 using the array_slice() method. Then, we will concatenate these two parts in reverse order using the array_merge() method to obtain the left rotated array.
Example: This example uses array slicing technique to left rotate array by d positions.
<?php
function leftRotateArray($arr, $d) {
$newArray = array_merge(
array_slice($arr, $d),
array_slice($arr, 0, $d)
);
return $newArray;
}
// Driver code
$arr = [1, 2, 3, 4, 5];
$d = 2;
$result = leftRotateArray($arr, $d);
// Print the array elements
foreach ($result as $element) {
echo $element . " ";
}
?>
Output
3 4 5 1 2
Using array_shift() and array_push() Functions
In this approach, we iterate through the array d times. In each iteration, we use array_shift() to remove the first element of the array and array_push() to add it to the end. This process effectively shifts each element d positions to the left. Finally, we return the modified array.
Example: This example uses array_shift() and array_push() functions to left rotate array by d positions.
<?php
function leftRotate($arr, $d) {
for ($i = 0; $i < $d; $i++) {
$element = array_shift($arr);
array_push($arr, $element);
}
return $arr;
}
// Driver code
$arr = [1, 2, 3, 4, 5, 6, 7];
$d = 3;
$result = leftRotate($arr, $d);
foreach ($result as $element) {
echo $element . " ";
}
?>
Output
4 5 6 7 1 2 3
Using a Temporary Array
In this approach, we:
- Store the first d elements in a temporary array.
- Shift the remaining elements in the original array to the left.
- Copy the elements from the temporary array to the end of the original array.
Example: This example uses a temporary array to left rotate the array by d positions.
<?php
function leftRotateWithTempArray($arr, $d) {
$n = count($arr);
$temp = array_slice($arr, 0, $d); // Step 1: Store the first d elements in a temporary array
// Step 2: Shift the remaining elements to the left
for ($i = $d; $i < $n; $i++) {
$arr[$i - $d] = $arr[$i];
}
// Step 3: Copy the elements from the temporary array to the end
for ($i = 0; $i < $d; $i++) {
$arr[$n - $d + $i] = $temp[$i];
}
return $arr;
}
// Driver code
$arr = [1, 2, 3, 4, 5, 6, 7];
$d = 2;
$result = leftRotateWithTempArray($arr, $d);
// Print the array elements
foreach ($result as $element) {
echo $element . " ";
}
?>
Output
3 4 5 6 7 1 2