PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 4.17 Sorting an Array

4.17.1 Problem

You want to sort an array in a specific way.

4.17.2 Solution

To sort an array using the traditional definition of sort, use sort( ):

$states = array('Delaware', 'Pennsylvania', 'New Jersey');
sort($states);

To sort numerically, pass SORT_NUMERIC as the second argument to sort( ).

$scores = array(1, 10, 2, 20);
sort($scores, SORT_NUMERIC);

This resorts the numbers in ascending order (1, 2, 10, 20) instead of lexicographical order (1, 10, 2, 20).

4.17.3 Discussion

The sort( ) function doesn't preserve the key/value association between elements; instead, entries are reindexed starting at 0 and going upward. (The one exception to this rule is a one-element array; its lone element doesn't have its index reset to 0. This is fixed as of PHP 4.2.3.)

To preserve the key/value links, use asort( ). The asort( ) function is normally used for associative arrays, but it can also be useful when the indexes of the entries are meaningful:

$states = array(1 => 'Delaware', 'Pennsylvania', 'New Jersey');
asort($states);

while (list($rank, $state) = each($states)) {
    print "$state was the #$rank state to join the United States\n";

}

Use natsort( ) to sort the array using a natural sorting algorithm. Under natural sorting, you can mix strings and numbers inside your elements and still get the right answer.

$tests = array('test1.php', 'test10.php', 'test11.php', 'test2.php');
natsort($tests);

The elements are now ordered: 'test1.php', 'test2.php', 'test10.php', and 'test11.php'. With natural sorting, the number 10 comes after the number 2; the opposite occurs under traditional sorting. For case-insensitive natural sorting, use natcasesort( ).

To sort the array in reverse order, use rsort( ) or arsort( ), which is like rsort( ) but also preserves keys. There is no natrsort( ) or natcasersort( ). You can also pass SORT_NUMERIC into these functions.

4.17.4 See Also

Recipe 4.18 for sorting with a custom comparison function and Recipe 4.19 for sorting multiple arrays; documentation on sort( ) at http://www.php.net/sort, asort( ) at http://www.php.net/asort, natsort( ) at http://www.php.net/natsort, natcasesort( ) at http://www.php.net/natcasesort, rsort( ) at http://www.php.net/rsort, and arsort( ) at http://www.php.net/arsort.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    4.1 Introduction
    Recipe 4.2 Specifying an Array Not Beginning at Element 0
    Recipe 4.3 Storing Multiple Elements per Key in an Array
    Recipe 4.4 Initializing an Array to a Range of Integers
    Recipe 4.5 Iterating Through an Array
    Recipe 4.6 Deleting Elements from an Array
    Recipe 4.7 Changing Array Size
    Recipe 4.8 Appending One Array to Another
    Recipe 4.9 Turning an Array into a String
    Recipe 4.10 Printing an Array with Commas
    Recipe 4.11 Checking if a Key Is in an Array
    Recipe 4.12 Checking if an Element Is in an Array
    Recipe 4.13 Finding the Position of an Element in an Array
    Recipe 4.14 Finding Elements That Pass a Certain Test
    Recipe 4.15 Finding the Largest or Smallest Valued Element in an Array
    Recipe 4.16 Reversing an Array
    Recipe 4.17 Sorting an Array
    Recipe 4.18 Sorting an Array by a Computable Field
    Recipe 4.19 Sorting Multiple Arrays
    Recipe 4.20 Sorting an Array Using a Method Instead of a Function
    Recipe 4.21 Randomizing an Array
    Recipe 4.22 Shuffling a Deck of Cards
    Recipe 4.23 Removing Duplicate Elements from an Array
    Recipe 4.24 Finding the Union, Intersection, or Difference of Two Arrays
    Recipe 4.25 Finding All Element Combinations of an Array
    Recipe 4.26 Finding All Permutations of an Array
    Recipe 4.27 Program: Printing an Array in a Horizontally Columned HTML Table
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele