Current Location: Home> Function Categories> usort

usort

Sort arrays by value using user-defined comparison functions
Name:usort
Category:Array
Programming Language:php
One-line Description:Sort arrays using user-defined comparison functions.

Definition and usage

usort() sorts the array through a user-defined comparison function.

Example

Use a user-defined comparison function to sort elements in array $a:

 <?php
function my_sort ( $a , $b )
{
if ( $a == $b ) return 0 ;
return ( $a < $b ) ? - 1 : 1 ;
}

$a = array ( 4 , 2 , 8 , 6 ) ;
usort ( $a , "my_sort" ) ;
?>

Try it yourself

grammar

 usort ( array , myfunction ) ;
parameter describe
array Required. Specifies the array to be sorted.
myfunction Optional. Defines a string that calls the comparison function. If the first parameter is less than or greater than the second parameter, the comparison function must return an integer less than or greater than 0.

illustrate

usort() function uses user-defined functions to sort arrays.

Note: If the comparison results of two elements are the same, the order in which they are in the sorted array is undefined. Until PHP 4.0.6, user-defined functions retain the original order of these elements. However, due to the introduction of a new sorting algorithm in 4.1.0, the result will not be this because there is no effective solution to this.

Note: This function assigns new key names to elements in the array . This will delete the original key name.

Similar Functions
  • Reversely sort the array by key name krsort

    krsort

    Reverselysortthearra
  • Split the array into blocks array_chunk

    array_chunk

    Splitthearrayintoblo
  • Reverse sorting of arrays rsort

    rsort

    Reversesortingofarra
  • Point the inner pointer of the array to the first unit reset

    reset

    Pointtheinnerpointer
  • Disrupt the array shuffle

    shuffle

    Disruptthearray
  • Alias ​​for current pos

    pos

    Alias​​forcurrent
  • Create an array based on range, containing specified elements range

    range

    Createanarraybasedon
  • Fill the array with specified keys and values array_fill_keys

    array_fill_keys

    Fillthearraywithspec
Popular Articles