English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP uasort() Function Usage and Example

PHP Array Function Manual

The uasort() function sorts the values in the array using a user-defined comparison function and maintains the index association

Syntax

uasort ( $array, $cmp_function )

Definition and Usage

This function sorts the array to keep the array index in correlation with the associated array elements. It is mainly used for sorting associative arrays where the actual element order is very important. The comparison function is user-defined.

Parameter

Serial NumberParameters and Description
1

array(Required)

It specifies an array.

2

cmp_function(Required)

If the function is defined, it is used to compare the values and sort them.

The function must return-1、0 or1,this method can work normally. It should be written to accept two parameters for comparison, and its working method should be similar to the following−

  • If a = b, then return 0

  • If a > b, then return1

  • If a < b, then return-1

Return Value

Returns TRUE on success, FALSE on failure.

Online Example

<?php
   function cmp_function($a, $b) {
      if ($a == $b) return 0;
      return ($a > $b) ? -1 : 1;
   }
   
   $input = array("d"=>"lemon", "a"=>"orange", "b"=>"banana" );
   uasort($input, "cmp_function");
   
   print_r($input);
?>
Test and see‹/›

Output Result:

Array ( [a] => orange [d] => lemon [b] => banana )

  PHP Array Function Manual