Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array - that specific values will be first

I have a array. for example:

   array("Apple", "Orange", "Banana", "Melon");

i want to sort the array that first will be "orange", "melon". and the array will be

   array( "Orange" , "Melon","Apple","Banana");

i looked in PHP sort functions, didn't find a s sort function to do it.
what is the right way to do it.
thank you

like image 963
BenB Avatar asked Jan 10 '23 23:01

BenB


1 Answers

What you looking for is usort, you can specify custom function to sort the array

example:

function cmp($a, $b)
{
    if ($a == "Orange") {
        return 1;
    }
    if ($b == "Orange") {
        return -1;
    }

    return strcmp($a, $b);// or any other sort you want
}

$arr = array("Apple", "Orange", "Banana", "Melon");

usort($arr, "cmp");
like image 139
Dima Avatar answered Jan 18 '23 23:01

Dima