is it possible to easily \'rotate\' an array in PHP ?
Like this: 1, 2, 3, 4 -> 2, 3 ,4 ,1
Is there some kind of built-in PHP function for this?
you can use this function:
function arr_rotate(&$array,$rotate_count) {
for ($i = 0; $i < $rotate_count; $i++) {
array_push($array, array_shift($array));
}
}
usage:
$xarr = array('1','2','3','4','5');
arr_rotate($xarr, 2);
print_r($xarr);
result:
Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 1 [4] => 2 )
Use array_shift and array_push.
Most of the current answers are correct, but only if you don't care about your indices:
$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');
array_push($arr, array_shift($arr));
print_r($arr);
Output:
Array
(
[baz] => qux
[wibble] => wobble
[0] => bar
)
To preserve your indices you can do something like:
$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');
$keys = array_keys($arr);
$val = $arr[$keys[0]];
unset($arr[$keys[0]]);
$arr[$keys[0]] = $val;
print_r($arr);
Output:
Array
(
[baz] => qux
[wibble] => wobble
[foo] => bar
)
Perhaps someone can do the rotation more succinctly than my four-line method, but this works anyway.
There's a task about array rotation on Hackerrank: https://www.hackerrank.com/challenges/array-left-rotation/problem.
And proposed solution with array_push
and array_shift
will work for all test cases except the last one, which fails due to timeout. So, array_push
and array_shift
will give you not the fastest solution.
Here's the faster approach:
function leftRotation(array $array, $n) {
for ($i = 0; $i < $n; $i++) {
$value = array[$i]; unset(array[$i]); array[] = $value;
}
return array;
}
The logic is to swap the elements. Algorithm may look like -
for i = 0 to arrayLength - 1
swap( array[i], array[i+1] ) // Now array[i] has array[i+1] value and
// array[i+1] has array[i] value.
No. Check the documentation for array_shift and its related functions for some tools you can use to write one. There might even be an array_rotate
function implemented in the comments of that page.
It's also worth reading through the array functions listed on the left-hand sidebar to get a full understanding of what array functions are available in PHP.