PHP: 'rotate' an array?

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

    Here's a function to rotate an array (zero-indexed array) to any position you want:

    function rotateArray($inputArray, $rotateIndex) {
      if(isset($inputArray[$rotateIndex])) {
        $startSlice = array_slice($inputArray, 0, $rotateIndex);
        $endSlice = array_slice($inputArray, $rotateIndex);
        return array_merge($endSlice, $startSlice);
      }
      return $inputArray;
    }
    
    $testArray = [1,2,3,4,5,6];
    $testRotates = [3, 5, 0, 101, -5];
    
    foreach($testRotates as $rotateIndex) {
      print_r(rotateArray($testArray, $rotateIndex));
    }
    

提交回复
热议问题