How to use usort() Function In PHP
The usort() function sorts an array by values using a user-defined comparison function. This is useful when you need a custom sorting logic.
Example: This example shows the implementation of the above-explained approach.
<?php
// Create an Array
$arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
// Compare function
function customCompare($a, $b) {
return $a - $b;
}
usort($arr, "customCompare");
print_r($arr);
?>
Output
Array
(
[0] => 1
[1] => 1
[2] => 2
[3] => 3
[4] => 3
[5] => 4
[6] => 5
[7] => 5
[8] => 5
[9] => 6
[10] => 9
)
How to Sort Numeric Array in PHP?
Given a numeric array, the task is to sort the numeric array using PHP. There are various built-in functions to sort arrays in different ways.
Below are the approaches to sort numeric arrays in PHP:
Table of Content
- Using sort() Function
- Using rsort() Function
- Using asort() Function
- Using arsort() Function
- Using usort() Function