0

I have one dynamic array, for example with following elements:

$myArray = array(1, 2, 3, 4, 5);

And I want my final array to be:

$finalArray = array(4, 1, 5, [whaterever]);

What's the best way to do custom sorting which is neither ascending or descending or doesn't follow any rule like this?
Thanks for your suggestions.

[Edit] I have edited my question.

MagePsycho
  • 1,876
  • 2
  • 27
  • 56
  • can you explain some more? – Chetan Ameta Feb 12 '16 at 09:54
  • When you have array with certain values and you want the values to be re-ordered like 4 at first 3 at last (as mentioned in above example). So may be a extra function where you mention the sorting posting for values and will return the sorted version of that array? – MagePsycho Feb 12 '16 at 09:57

1 Answers1

3

You can try the usort function. On the second argument, you should write a function that will decide how your array elements should be placed.

Something like this:

<?php
$myArray = [1, 2, 3, 4, 5];

$properOrder = [4, 1, 5, 2, 3];
usort($myArray, function($a, $b) use($properOrder) {
    $index1 = array_search($a, $properOrder);
    $index2 = array_search($b, $properOrder);

    if ($index1 > $index2) {
        return 1;
    } else if ($index1 < $index2) {
        return -1;
    } else {
        return 0;
    }
});

print_r($myArray);
antoniom
  • 2,771
  • 1
  • 32
  • 47
  • It's not working now. I want to have final array to have `array(4, 1, 5, [whaterever])` – MagePsycho Feb 12 '16 at 12:35
  • @MagePsycho 1st Your question is now different than the original, so consider asking a new question. 2nd You should try to edit the custom function on the answer so that it returns -1 when your index is not 4, 1 or 5. We are here to help, and to point you to the right direction. Not to do your homework or your job. – antoniom Feb 12 '16 at 14:18
  • here it is - http://stackoverflow.com/questions/35365385/custom-sorting-for-first-few-elements-of-an-array – MagePsycho Feb 12 '16 at 14:49