3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Reposition an array element by on its key. * * @param array $array The array being reordered. * @param string|int $key They key of the element you want to reposition. * @param int $order The position in the array you want to move the element to. (0 is first) * * @throws \Exception */ function repositionArrayElement(array &$array, $key, int $order): void { if(($a = array_search($key, array_keys($array))) === false){ throw new \Exception("The {$key} cannot be found in the given array."); } $p1 = array_splice($array, $a, 1); $p2 = array_splice($array, 0, $order); $array = array_merge($p2, $p1, $array); } $fruits = [ 'bananas'=>'12', 'apples'=>'23', 'tomatoes'=>'21', 'nuts'=>'22', 'foo'=>'a', 'bar'=>'b' ]; repositionArrayElement($fruits, "foo", 1); var_export($fruits); $colours = ["green", "blue", "red"]; repositionArrayElement($colours, 2, 0); var_export($colours);
Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1
array ( 'bananas' => '12', 'foo' => 'a', 'apples' => '23', 'tomatoes' => '21', 'nuts' => '22', 'bar' => 'b', )array ( 0 => 'red', 1 => 'green', 2 => 'blue', )

preferences:
76.57 ms | 407 KiB | 5 Q