3v4l.org

run code in 300+ PHP versions simultaneously
<?php $allOptions = array( array("clID"=> 171), array("clID"=> 191), array("clID"=> 131), array("clID"=> 101), array("clID"=> 201), array("clID"=> 181), array("clID"=> 99), // not in regOptions array("clID"=> 129), // not in regOptions array("clID"=> 139), ) ; $regOptions = array( array("order"=>1,"optID"=> 131), array("order"=>2,"optID"=> 191), array("order"=>3,"optID"=> 181), array("order"=>4,"optID"=> 139), array("order"=>5,"optID"=> 101), array("order"=>6,"optID"=> 201), array("order"=>7,"optID"=> 171) ); // add indexes to the original array for faster lookups $indexedOptions = []; foreach($allOptions as $val) { $indexedOptions[$val['clID']] = $val; } $newArray = []; foreach ($regOptions as $order) { $id = $order['optID']; if (isset($indexedOptions[$id])) { $newArray[] = $indexedOptions[$id]; unset($indexedOptions[$id]); } } // at this point, $newArray has all of the found values in order, // and $indexedOptions has any remaining items. // var_dump($newArray); // var_dump($indexedOptions); // put them together for the final array $final = array_merge($newArray, $indexedOptions); var_dump($final);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
array(9) { [0]=> array(1) { ["clID"]=> int(131) } [1]=> array(1) { ["clID"]=> int(191) } [2]=> array(1) { ["clID"]=> int(181) } [3]=> array(1) { ["clID"]=> int(139) } [4]=> array(1) { ["clID"]=> int(101) } [5]=> array(1) { ["clID"]=> int(201) } [6]=> array(1) { ["clID"]=> int(171) } [7]=> array(1) { ["clID"]=> int(99) } [8]=> array(1) { ["clID"]=> int(129) } }

preferences:
65.14 ms | 408 KiB | 5 Q