How to useArray Slice() Function in PHP
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
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