Skip to content

Instantly share code, notes, and snippets.

@SabrinaMarkon
Last active December 24, 2018 07:15
Show Gist options
  • Save SabrinaMarkon/0b5757e39b5b23b514e43178a64c0853 to your computer and use it in GitHub Desktop.
Save SabrinaMarkon/0b5757e39b5b23b514e43178a64c0853 to your computer and use it in GitHub Desktop.
PHP arrays - rotate array items left d times without using built-in array_pop, array_shift. Uses array_values so times out HackerRank challenge.
<?php
// array to rotate
$a = [1,2,3,4,5];
// the number of left rotations
$d = 4;
// we want 5,1,2,3,4 as the end result
for ($i = 0; $i < $d; $i++) {
// size of array is next position to add on to the end
$next = sizeof($a);
// the value of the front of the array (like a queue)
$current = $a[0];
// remove the item at the front of the array which is saved now into currentval
unset($a[0]);
// take current value and add it to the end of the array instead
$a[$next] = $current;
// reset the array's indexing
$a = array_values($a);
}
// rotated array (return $a in function where you pass $a and $d)
print_r($a);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment