PHP: 'rotate' an array?

后端 未结 14 1827
小鲜肉
小鲜肉 2020-11-28 14:16

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?

14条回答
  •  执念已碎
    2020-11-28 15:01

    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.

提交回复
热议问题