<?php
function sorter($array) {
// find the key which doesn't have a matching value
$unique = array_diff(array_keys($array), $array);
$key = reset($unique);
$value = $array[$key];
$result = array($key => $value);
// follow the values backwards until the key matches the value
while ($key != $value) {
$key = $array[$key];
$value = $array[$key];
$result = array($key => $value) + $result;
}
return $result;
}
$main = array(
'lorem' => 'lorem',
'ipsum' => 'duis',
'sit' => 'adipiscing',
'duis' => 'sit',
'amet' => 'elit',
'consectetur' => 'lorem',
'adipiscing' => 'consectetur',
'eiusmod' => 'ipsum',
'labore' => 'eiusmod',
'dolore' => 'labore',
'magna' => 'dolore',
'aliqua' => 'amet',
'incididunt' => 'magna',
'tempor' => 'incididunt',
'sed' => 'tempor',
'elit' => 'sed',
);
print_r(sorter($main));
preferences:
25.5 ms | 407 KiB | 5 Q