PhpDig.net

What is PhpDig?
PhpDig is a PHP MySQL based
Web Spider & Search Engine.




usort

Name

usort — Sorts the given scalar array with a user-defined function.

Synopsis

bool usort(array, func);
array array: Array to sort using the supplied function
string func: Function to use to sort the array

Returns

TRUE on success; FALSE on error

Description

usort() sorts array according to the user-defined function named by func . This can be useful for doing sorts with custom algorithms or doing non-case-sensitive sorts with alphabetic characters. When you pass usort() an array and the name of a user-defined function, it uses the bubblesort method and traverses the elements of the array to sort them. The custom function must return -1, 0, or 1 for this method to work correctly (see example). If used on an associative array, this function causes the keys to be destroyed while sorting on the values.

func should be written to accept two parameters, which it compares. If they're considered equivalent, 0 should be returned. If the first is considered to be greater, 1 should be returned. If the second is considered to be greater, -1 should be returned.

Version

PHP 3 since 3.0.3, PHP 4

Example

Example 62. Sort an array using a user-defined comparison function

function usort_cmp($a, $b) {
   if ($a == $b) return 0;
   return ($a > $b) ? -1 : 1;
}

$arr = array("Banana", "carrot",
             "Apple", "banana",
             "apple", "Carrot");
usort($arr, "usort_cmp");
while(list($k, $v) = each($arr)) {
   echo "$k => $v\n";
}

Output:
0 => Apple
1 => Banana
2 => Carrot
3 => apple
4 => banana
5 => carrot



PHP Functions Essential Reference. Copyright © 2002 by New Riders Publishing (Authors: Zak Greant, Graeme Merrall, Torben Wilson, Brett Michlitsch). This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). The authors of this book have elected not to choose any options under the OPL. This online book was obtained from http://www.fooassociates.com/phpfer/ and is designed to provide information about the PHP programming language, focusing on PHP version 4.0.4 for the most part. The information is provided on an as-is basis, and no warranty or fitness is implied. All persons and entities shall have neither liability nor responsibility to any person or entity with respect to any loss or damage arising from the information contained in this book.

Powered by: vBulletin Version 3.0.7
Copyright ©2000 - 2005, Jelsoft Enterprises Ltd.
Copyright © 2001 - 2005, ThinkDing LLC. All Rights Reserved.