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
Approach 1: 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
Approach 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
Contact Us