<?php
function orderByKeys(array $array, array $keys)
{
foreach ($keys as $k => $v) {
if (!array_key_exists($v, $array)) {
unset($keys[$k]);
}
}
return array_replace(array_flip($keys), $array);
}
$data = [
'orange' => 'orange',
'apple' => 'tasty',
'carpet' => 'old',
'car' => 'fast',
];
$result = orderByKeys($data, ['car', 'carpet']);
//Would result in:
$data = [
'car' => 'fast',
'carpet' => 'old',
'orange' => 'orange',
'apple' => 'tasty',
];