Skip to content

Instantly share code, notes, and snippets.

@dmdeller
Created January 22, 2010 16:38
Show Gist options
  • Save dmdeller/283895 to your computer and use it in GitHub Desktop.
Save dmdeller/283895 to your computer and use it in GitHub Desktop.
<?php
/**
* reorders an array based on the specified order of keys.
*
* @param array $array the array that should be reordered
* @param array $order the order that the keys in the first array should be in. each value should be a key from the first array. any elements from the first array that are not specified in the order will be inserted at the end of the returned array, in their original order.
*
* @return array
*/
function reorder(array $array, array $order)
{
$new_array = array();
// add elements to the new array in the correct order
foreach ($order as $key)
{
// skip any keys that were not in the array
if (isset($array[$key]))
{
$new_array[$key] = $array[$key];
}
}
// add any remaining elements that were not specified in the order
foreach ($array as $key => $val)
{
if (!isset($new_array[$key]))
{
$new_array[$key] = $val;
}
}
return $new_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment