3

I'm struggling trying to sort an array via the normal functions, i'm sure this needs a custom comparison function but none the less will chuck this out there.

I have an array with 5 elements inside it. I would like the array to sort itself like so, arsort came close but not quite:

4,0,1,2,3

Just to clarify, the position of the array like: $array[0];

I haven't actually looked at array comparison functions before, so a push in the right direction would be most helpful to solve this!

Thanks,

Adam

evensis
  • 172
  • 3
  • 15
  • You can use [`usort()`](http://php.net/usort) to sort an array via a custom comparison function. – Carsten Mar 08 '13 at 13:23

3 Answers3

18

This method will sort an array using a pre-defined order of keys using uksort

$desiredIndexOrder = array(4 => 1, 0 => 2, 1 => 3, 2 => 4, 3 => 5);

uksort($inputArray, function($a, $b) use ($desiredIndexOrder) {
    return $desiredIndexOrder[$a] > $desiredIndexOrder[$b] ? -1 : 1;
});

Notice the $desiredIndexOrder array is in index => desired sort position format. If you don't want to put your array in that format, you can have it built for you using this:

$desiredIndexOrder = array();

foreach ($desiredKeyOrder as $position=>$key) {
    $desiredIndexOrder[$key] = $position + 1;
}

Where $desiredKeyOrder is the array order of your keys: array(4, 0, 1, 2, 3)

Andy
  • 698
  • 12
  • 22
Colin M
  • 13,010
  • 3
  • 38
  • 58
  • Thanks Colin, this was exactly what I was after. Also using the comparative function answered my question perfectly. – evensis Mar 08 '13 at 13:42
0

Try this

$array = array('t','r','a','c','k');
$keys = '4,0,1,2,3';

$keyArr = explode(',', $keys);
$sarr = array();

foreach ($keyArr as $key)
{
    $sarr[$key] = $array[$key];
}
print_r($sarr);
Nirmal Ram
  • 1,722
  • 4
  • 25
  • 45
0

Try this :

$numbers = array(1,2,3,4,5);
array_unshift($numbers, array_pop($numbers));

echo "<pre>";
print_r($numbers);

Output :

Array
(
    [0] => 5
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
)
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73