3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $orders = array(1,2,3,4,5); $index = 2; $newOrder = 1; // 3,1,2,4,5 function reorder($index, $newOrder, $orders) { $newOrders = array(); $oldOrder = $index; $item = $orders[$index]; $newOrders[$index] = $item; $lowers = array(); $uppers = array(); $direction = index - $newOrder; foreach ($orders as $i => $v) { if ($i < $index) { $lowers[] = $i; } if ($i > $index) { $uppers[] = $i; } } if ($direction < 0) { foreach ($lowers as $i => $v) { $newOrders[$v + 1] = $orders[$v]; } foreach ($uppers as $i => $v) { $newOrders[$v] = $orders[$v]; } } else { foreach ($uppers as $i => $v) { $newOrders[$v - 1] = $orders[$v]; } foreach ($lowers as $i => $v) { $newOrders[$v] = $orders[$v]; } } //ksort($newOrders); var_dump($newOrders); } reorder($index, $newOrder, $orders);
based on rCSTV
Output for 7.2.0
Warning: Use of undefined constant index - assumed 'index' (this will throw an Error in a future version of PHP) in /in/603Wm on line 13 Warning: A non-numeric value encountered in /in/603Wm on line 13 array(4) { [2]=> int(2) [1]=> int(1) [3]=> int(4) [4]=> int(5) }
Output for 7.1.0 - 7.1.10
Notice: Use of undefined constant index - assumed 'index' in /in/603Wm on line 13 Warning: A non-numeric value encountered in /in/603Wm on line 13 array(4) { [2]=> int(2) [1]=> int(1) [3]=> int(4) [4]=> int(5) }
Output for 5.3.19 - 7.0.20
Notice: Use of undefined constant index - assumed 'index' in /in/603Wm on line 13 array(4) { [2]=> int(2) [1]=> int(1) [3]=> int(4) [4]=> int(5) }