PHP: 'rotate' an array?

后端 未结 14 1662
小鲜肉
小鲜肉 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 14:59

    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 )
    
    0 讨论(0)
  • 2020-11-28 15:00

    Use array_shift and array_push.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 15:01

    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;
    }
    
    0 讨论(0)
  • 2020-11-28 15:01

    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.
    
    0 讨论(0)
  • 2020-11-28 15:07

    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.

    0 讨论(0)
提交回复
热议问题