Skip to content

Instantly share code, notes, and snippets.

@rseon
Last active April 8, 2019 12:28
Show Gist options
  • Save rseon/d0ee839c55ca5b6dec48cb4fc387ad6c to your computer and use it in GitHub Desktop.
Save rseon/d0ee839c55ca5b6dec48cb4fc387ad6c to your computer and use it in GitHub Desktop.
Sort an array by keys based on specified order (without changing association)
<?php
// Our initial array
$array_in = [
'L' => 'foo',
'R' => 'bar',
'skibidi' => 'wapwapwap',
3 => 'baz',
'V' => 'qux',
];
// The desired sort, adding a non-existent key and forgetting another to see what happens
$array_order = ['V', 'L', 3, 'foo', 'R'];
// The sorted array
$array_out = array_replace(array_flip($array_order), $array_in);
/*
Result: The non-existent key is added with its position as a value and the forgotten value is added at the end.
array (
'V' => 'qux',
'L' => 'foo',
3 => 'baz',
'foo' => 3,
'R' => 'bar',
'skibidi' => 'wapwapwap',
)
*/
// Another approach
$array_out2 = [];
foreach($array_order as $index => $key_name) {
if(array_key_exists($key_name, $array_in)) {
$array_out2[$key_name] = $array_in[$key_name];
}
else {
$array_out2[$key_name] = null;
}
}
/*
Result: The non-existing key is added with NULL as value.
array (
'V' => 'qux',
'L' => 'foo',
3 => 'baz',
'foo' => NULL,
'R' => 'bar',
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment