wilded
6/20/2017 - 8:11 AM

Function to rotate array elements to the left and right

Function to rotate array elements to the left and right

<?php

function rotate_array_left($array, $rotations){
	for ($r=0; $r<$rotations; $r++){
		array_push($array, array_shift($array));
	}
	return $array;
}

function rotate_array_right($array, $rotations){
	for ($r=0; $r<$rotations; $r++){
		array_unshift($array, array_pop($array));
	}
	return $array;
}


$n = 1; //Number of rotations

$a = array(1,2,3,4,5);
echo "Original Array with $n rotations ";
foreach($a as $value){
	echo $value . " ";
}
echo "<br>";

//Rotate Array Left
$b = rotate_array_left($a,$n);
foreach($b as $element){
	echo $element . " ";
}

print_r('<br>');

//Rotate Array Right
$b = rotate_array_right($a,$n);
foreach($b as $element){
	echo $element . " ";
}