Sorting One Array at a Time

PHP functions for sorting an array
Effect
Ascending
Descending
User-defined order
Sort array by values, then reassign indices starting with 0
sort( )
rsort( )
usort( )
Sort array by values
asort( )
arsort( )
uasort( )
Sort array by keys
ksort( )
krsort( )
uksort( )

The sort( ), rsort( ), and usort( ) functions are designed to work on indexed arrays because they assign new numeric keys to represent the ordering. They're useful when you need to answer questions such as, "What are the top 10 scores?" and "Who's the third person in alphabetical order?" The other sort functions can be used on indexed arrays, but you'll only be able to access the sorted ordering by using traversal functions such as foreach and next 

To sort names into ascending alphabetical order, you'd use this:
    $names = array('cath', 'angela', 'brad', 'dave');
    sort($names);                // $names is now 'angela', 'brad', 'cath', 'dave'

To get them in reverse alphabetic order, simply call rsort( ) instead of sort( ).
If you have an associative array mapping usernames to minutes of login time, you can use arsort( ) to display a table of the top three, as shown here:
    $logins = array('njt' => 415,
                    'kt'  => 492,
                    'rl'  => 652,
                    'jht' => 441,
                    'jj'  => 441,
                    'wt'  => 402);
    arsort($logins);
    $num_printed = 0;
    echo("<table>\n");
    foreach ($logins as $user => $time ) {
      echo("<tr><td>$user</td><td>$time</td></tr>\n");
      if (++$num_printed == 3) {
        break;                   // stop after three
      }
    }
    echo("</table>\n");
    <table>
    <tr><td>rl</td><td>652</td></tr>
    <tr><td>kt</td><td>492</td></tr>
    <tr><td>jht</td><td>441</td></tr>
    </table>

If you want that table displayed in ascending order by username, use ksort( ):
    ksort($logins);
    echo("<table>\n");
    foreach ($logins as $user => $time) {
      echo("<tr><td>$user</td><td>$time</td></tr>\n");
    }
    echo("</table>\n");
    <table>
    <tr><td>jht</td><td>441</td></tr>
    <tr><td>jj</td><td>441</td></tr>
    <tr><td>kt</td><td>492</td></tr>
    <tr><td>njt</td><td>415</td></tr>
    <tr><td>rl</td><td>652</td></tr>
    <tr><td>wt</td><td>402</td></tr>
    </table>

User-defined ordering requires that you provide a function that takes two values and returns a value that specifies the order of the two values in the sorted array. The function should return 1 if the first value is greater than the second, -1 if the first value is less than the second, and 0 if the values are the same for the purposes of your custom sort order.
 a program that lets you try the various sorting functions on the same data.

 
Related Posts:
  • Creating Arrays PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use: $numbers = array(5, 4, 3, 2, 1);… Read More
  • Length of a String The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string: integer strlen(string subject) We used strlen( ) earlier in the chapter t… Read More
  • PHP Variable names Variable names always begin with a dollar sign ($) and are case-sensitive. Here aresome valid variable names:$pill$ad_count$dForce$I_kk_PHP$_underscore$_intHere are some illegal variable names:$not valid$|$3ka  These va… Read More
  • File Manipulation 11.3. File Manipulation There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't co… Read More
  • PHP Date / Time Functions checkdate — Validate a Gregorian date date_add — Alias of DateTime::add date_create_from_format — Alias of DateTime::createFromFormat date_create — Alias of DateTime::__construct date_date_set — Alias of DateTime::setDate … Read More
  • PHP Configuration Directives Although the focus of this book is application security, there are a few configuration directives with which any security-conscious developer should be familiar. The configuration of PHP can affect the behavior of the cod… Read More
  • PHP HTTP Functions ob_deflatehandler — Deflate output handler ob_etaghandler — ETag output handler ob_inflatehandler — Inflate output handler http_parse_cookie — Parse HTTP cookie http_parse_headers — Parse HTTP headers http_parse_message — P… Read More
  • Cleaning Strings Often, the strings we get from files or users need to be cleaned up before we can use them. Two common problems with raw data are the presence of extraneous whitespace, and incorrect capitalization (uppercase versus lowercas… Read More
  • PHP MySQL Functions mysql_field_len — Returns the length of the specified field mysql_field_name — Get the name of the specified field in a result mysql_field_seek — Set result pointer to a specified field offset mysql_field_table — Get … Read More
  • Substrings PHP If you know where in a larger string the interesting data lies, you can copy it out with the substr( ) function: $piece = substr(string, start [, length ]); The start argument is the position in string at which to begin copy… Read More
  • Defining Functions There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement: function some_function([argumen… Read More
  • PHP Array Functions array_change_key_case — Changes all keys in an array array_chunk — Split an array into chunks array_combine — Creates an array by using one array for keys and another for its values array_count_values — Counts all the value… Read More
  • Including and Requiring PHP Files To make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include in your PHP program… Read More
  • PHP - Echo <?php $myiString = "Hi!"; echo $myiString; echo "<h5>I love PHP!</h5>"; ?>   Display: Hi! I love  PHP!  A simple form example     1 <html> 2 <head> 3 <title&g… Read More
  • PHP Zip File Functions zip_close — Close a ZIP file archive zip_entry_close — Close a directory entry zip_entry_compressedsize — Retrieve the compressed size of a directory entry zip_entry_compressionmethod — Retrieve the compression meth… Read More