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

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP usort() Function Usage and Example

PHP Array Function Manual

The usort() function sorts the values in the array using a user-defined comparison function

Syntax

usort ($array, $cmp_function)

Definition and Usage

The usort() function sorts an array using a user-defined comparison function. This function assigns new keys to the elements of the array. Existing keys will be deleted.

Parameter

Serial NumberParameters and Description
1

array(Required)

It specifies an array.

2

cmp_function(Required)

Useful defined function, used to compare values and sort them.

  • Return 0 if a = b

  • Return if a > b1

  • Return if a < b-1

Return Value

Return TRUE on success, FALSE on failure.

Online Example

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

Output Result:

Array ( [0] => orange [1] => lemon [2] => banana )

  PHP Array Function Manual