$a = array('val1','val2',200, 179,230, 234, 242);
$b = array(230, 234, 242, 179, 100);
So array $a should be sorted according to array $b and $resultArray should be ('val1','val2',200, 230, 234, 242, 179)
$a = array('val1','val2',200, 179,230, 234, 242);
$b = array(230, 234, 242, 179, 100);
So array $a should be sorted according to array $b and $resultArray should be ('val1','val2',200, 230, 234, 242, 179)
Your sorting requirements:
Flipping your order lookup array will permit improved efficiency while processing before key searching is faster than value searching in php.
Code: (Demo)
$array = ['val1', 'val2', 200, 179, 230, 234, 242];
$order = [230, 234, 242, 179, 100];
$keyedOrder = array_flip($order); // for efficiency
usort($array, function($a, $b) use ($keyedOrder) {
return [$keyedOrder[$a] ?? -1, $a]
<=>
[$keyedOrder[$b] ?? -1, $b];
});
var_export($array);
Output:
array (
0 => 'val1',
1 => 'val2',
2 => 200,
3 => 230,
4 => 234,
5 => 242,
6 => 179,
)
$keyedOrder[$variable] ?? -1 effectively means if the value is not found in the lookup, use -1 to position the item before the lowest value in the lookup array (0). If the value IS found as a key in the lookup, then use the integer value assigned to that key in the lookup.
From PHP7.4, arrow function syntax can be used to make the snippet more concise and avoid the use() declaration.
usort($array, fn($a, $b) => [$keyedOrder[$a] ?? -1, $a] <=> [$keyedOrder[$b] ?? -1, $b]);