How can an array be sorted in PHP based on a custom-defined order?
When sorting an array in PHP based on a custom-defined order, you can use the `usort()` function along with a custom comparison function. This comparison function will define the order in which elements should be sorted. By specifying the desired order within the comparison function, you can achieve a custom sort based on your specific requirements.
// Define a custom order
$customOrder = ['apple', 'banana', 'cherry'];
// Sample array to be sorted
$fruits = ['cherry', 'banana', 'apple', 'orange'];
// Custom comparison function
function customSort($a, $b) {
global $customOrder;
return array_search($a, $customOrder) - array_search($b, $customOrder);
}
// Sort the array based on custom order
usort($fruits, 'customSort');
// Output sorted array
print_r($fruits);