Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL

Home > PHP > Sorting Arraysprinter version

PHP Sorting Arrays

The simplest sorting functions provided by PHP are sort() and rsort() which sort arrays in ascending and descending order respectively.

The sort() and rsort Functions

The sort() function takes the array as a parameter and sorts numeric values in numeric order and string values in alphabetical order.

The rsort() function does the same but in descending order.

Example of sort()
<?php
    $numbers = array (10, 35, 2, 12);

    sort ($numbers);

    // Print out the result
    foreach ($numbers as $number)
        echo($number.', ');

    // Which gives 2, 10, 12, 35,

    $names = array ("Tom", "Dick", "Harry");

    sort ($names);

    // Print out the result
    foreach ($names as $name)
        echo($name.', ');

    // Which gives Dick, Harry, Tom,
?>


The way these functions sort can be changed by using the optional parameter sort_flag.

The syntax is sort ($array, sort_flag) where sort_flag is one of the values shown below.



Note: Although sort() and rsort() can be used on associative arrays, the keys will be lost.

Sorting Associative arrays

If you don't wish the keys to be lost when you sort an associative array then the asort() and arsort() functions are available.

These work in the same way as sort() and rsort() but the keys are preserved.

Example of asort()
<?php
    $names = array ("first" => "Tom", "second" => "Dick", "third" => "Harry");

    asort ($names);

    // Print out the result
    foreach ($names as $index => $name)
        echo('['.$index.']'.$name.' ');

    // Which gives [second]Dick [third]Harry [first]Tom
?>


Note: . Although asort() and arsort() can be used on numbered arrays, PHP treats the indexes as keys and maintains the association of the keys with the values of the elements.

This means that the indexes won't run in order as you might expect.

Sorting by Key

The ksort() and krsort() functions work in the same way as asort() and arsort() except that the array is sorted by key instead of by element value.

Example of ksort()
<?php
    $names = array ("first" => "Tom", "next" => "Dick", "last" => "Harry");

    ksort ($names);

    // Print out the result
    foreach ($names as $index => $name)
        echo('['.$index.']'.$name.' ');

    // Which gives [first]Tom [last]Harry [next]Dick
?>


User-Defined Sorting

This requires a knowledge of functions, which is covered in the tutorial User Defined Functions.

PHP provides three functions to allow user-defined sorting.



The syntax of all three functions takes the form
usort ($array, cmp_function)
where cmp_function is the name of a user-defined function that compares two arguments (either element values or keys) to decide if they are equal, one is greater than the other or one is less the other.

The user-defined function is not called directly from within the script but its name passed as a parameter to the sort function. Functions used in this way are normally known as callback functions.

The function can be used to make any comparison you choose. Below is an example that compares the length of two strings and returns 0 if they're equal, 1 if the first is greater than the second and -1 if the first is less than the second.

Example of a Callback Function
<?php
    function compare_names ($name1, $name2)
    {
        if (strlen ($name1) > strlen ($name2)) return 1;
        if (strlen ($name1) < strlen ($name2)) return -1;
        return 0;
    }
?>


The function above can now be used to sort an array of names by their length.

User-Defined Sort
<?php
    $names = array ("Tom", "Dick", "Harry", "Ed", "George");

    usort ($names, "compare_names");

    // Print out the result
    foreach ($names as $name)
        echo($name.' ');

    // Which gives Ed Tom Dick Harry George
?>


Previous - PHP array functions Previous - Array Functions     Next - User-Defined Functions Next - PHP user-defined functions


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsArraysArray FunctionsPHP sorting arraysSorting ArraysUser-Defined FunctionsInclude and RequireUploading FilesFile FunctionsSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook
Tips and TricksPage TemplatesForm Reply ScriptsForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.