PHP: 'rotate' an array?

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

    A method to maintain keys and rotate. using the same concept as array_push(array, array_shift(array)), instead we will use array_merge of 2 array_slices

    $x = array("a" => 1, "b" => 2, "c" => 3, 'd' => 4);

    To move the First element to the end

    array_merge(array_slice($x, 1, NULL, true), array_slice($x, 0, 1, true) //'b'=>2, 'c'=>3, 'd'=>4, 'a'=>1

    To move the last element to the front

    array_merge(array_slice($x, count($x) -1, 1, true), array_slice($x, 0, //'d'=>4, 'a'=>1, 'b'=>2, 'c'=>3

提交回复
热议问题