Skip to content

Instantly share code, notes, and snippets.

@octlabs
Last active November 4, 2020 10:31
Show Gist options
  • Save octlabs/918a55a4aea1916a55d689d9cbb5005e to your computer and use it in GitHub Desktop.
Save octlabs/918a55a4aea1916a55d689d9cbb5005e to your computer and use it in GitHub Desktop.
sort array with defined key order
$arr = [
'x' => '1',
'foo' => 'me',
'y' => '2',
'bar' => '42',
'z' => '3',
];
/**
* sort array with defined key order (undefined keys remain in random order appended)
* $keys_order ['key name' => weight]
* from light -> heavy (sinking)
*/
$keys_order = [
'foo' => 1,
'bar' => 2,
];
uksort(
$arr,
fn($a, $b) =>
(isset($keys_order[$a]) ? $keys_order[$a] : PHP_INT_MAX)
- (isset($keys_order[$b]) ? $keys_order[$b] : PHP_INT_MAX)
);
/** Result:
Array
(
[foo] => me
[bar] => 42
[x] => 1
[y] => 2
[z] => 3
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment