phparraysrotationshift

Rotate array elements to the left (move first element to last and re-index)


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?


Solution

  • 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.