How to usearray_shift() and array_push() Functions in PHP
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
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
Contact Us