To rotate elements in an array using PHP, you can use the built-in array functions like array_slice
and array_merge
.
In this example,
$intArray
containing integers.array_slice
function to extract and rotate elements from $intArray
.array_merge
function to combine the rotated and remaining elements.<?php
$intArray = [1, 2, 3, 4, 5];
$positions = 2;
$rotatedArray = array_merge(array_slice($intArray, $positions), array_slice($intArray, 0, $positions));
print_r($rotatedArray);
?>
Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 1 [4] => 2 )
In this example,
$strArray
containing strings.array_slice
function to extract and rotate elements from $strArray
.array_merge
function to combine the rotated and remaining elements.<?php
$strArray = ['apple', 'banana', 'cherry', 'date', 'fig'];
$positions = 3;
$rotatedArray = array_merge(array_slice($strArray, $positions), array_slice($strArray, 0, $positions));
print_r($rotatedArray);
?>
Array ( [0] => date [1] => fig [2] => apple [3] => banana [4] => cherry )
In this tutorial, we learned How to Rotate Elements in an Array in PHP language with well detailed examples.