PHP | usort() Function
PHP comes with a number of built-in functions which is used to sort arrays in an easier way. Here, we are going to discuss a new function usort(). The usort() function in PHP sorts a given array by using user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to elements present in the array and the old keys are lost.
Syntax:
boolean usort( $array, "function_name");
Parameters: This function accepts two parameters as shown in the above syntax and are described below:
- $array: This parameter specifies the array which u want to sort.
- function_name : This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two argument are equal then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.
Return Value: This function returns boolean type of value. It returns TRUE in case of success and FALSE in case of failure.
Below program illustrate the usort() function in PHP:
<?php // PHP program to ilustrate usort() function // This is the user-defined function used to compare // values to sort the input array function comparatorFunc( $x, $y) { // If $x is equal to $y it returns 0 if ($x== $y) return 0; // if x is less than y then it returns -1 // else it returns 1 if ($x < $y) return -1; else return 1; } // Input array $arr= array(2, 9, 1, 3, 5); usort($arr, "comparatorFunc"); print_r($arr); ?> |
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
[4] => 9
)
Reference:
http://php.net/manual/en/function.usort.php
Recommended Posts:
- How to call a function that return another function in JavaScript ?
- How to get the function name from within that function using JavaScript ?
- How to get the function name inside a function in PHP ?
- D3.js | d3.max() function
- PHP | Ds\Map put() Function
- D3.js | d3.hsl() Function
- PHP | end() Function
- PHP | sin( ) Function
- PHP | pow( ) Function
- PHP | pos() Function
- PHP | Ds\Map last() Function
- PHP | Ds\Map map() Function
- PHP | tan( ) Function
- p5.js | hex() function
- PHP | dir() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



