I have a array. for example:
array(\"Apple\", \"Orange\", \"Banana\", \"Melon\");
i want to sort the array that first will be \"orange\
Here's a solution that's longer than the others provided, but more flexible. You can easily expand or change the array of items that you want sorted first.
$array = array("Apple", "Orange", "Banana", "Melon");
$sort_first = array("Orange", "Melon");
usort($array, function ($a, $b) use ($sort_first) {
$order_a = array_search( $a, $sort_first );
$order_b = array_search( $b, $sort_first );
if ($order_a === false && $order_b !== false) {
return 1;
} elseif ($order_b === false && $order_a !== false) {
return -1;
} elseif ($order_a === $order_b) {
return $a <=> $b;
} else {
return $order_a <=> $order_b;
}
});
// Result: $array = array("Orange", "Melon", "Apple", "Banana");
The function can also be easily altered if the items you're sorting aren't strings, such as arrays or objects. Here's an example that sorts an array of objects:
// Assuming $array is an array of users with a getName method
$sort_first = array("Sam", "Chris");
usort($array, function ($a, $b) use ($sort_first) {
$order_a = array_search( $a->getName(), $sort_first );
$order_b = array_search( $b->getName(), $sort_first );
if ($order_a === false && $order_b !== false) {
return 1;
} elseif ($order_b === false && $order_a !== false) {
return -1;
} elseif ($order_a === $order_b) {
return $a->getName() <=> $b->getName();
} else {
return $order_a <=> $order_b;
}
});
// $array will now have users Sam and Chris sorted first,
// and the rest in alphabetical order by name