ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Sort array alphabetically

This function, used in conjunction with the usort() function, allows you to sort a n array alphabetically, e.g. usort($feeds, “cmp”);

// Function to sort array alphabetically
function cmp($a$b) {
return 
strnatcasecmp$a['TITLE'], $b['TITLE'] );
}
?>

2 Responses to “Sort array alphabetically”

  1. BraveBrain Says:

    Note that the above function is for sorting multidimensional arrays.
    I.e. if you had the following code after the function

    $feeds[0][”TITLE”] = “Superman”;
    $feeds[0][”RATING”] = 4;
    $feeds[0][”STATUS”] = “Sold”;
    $feeds[1][”TITLE”] = “Addams Family”;
    $feeds[1][”RATING”] = 3;
    $feeds[2][”TITLE”] = “Winnie the Pooh”;
    $feeds[2][”RATING”] = 5;
    usort($feeds, “cmp”);

    Would sort alphabetically by title like this
    array(3) {
    [0]=> array(2) {
    [0] Addams Family
    [1] 3
    }
    [1]=> array(2){
    [0] Superman
    [1] 5
    [2] Sold
    }
    [2]=> array(2){
    [0] Winnie the Pooh
    [1] 4
    }
    }

    For regular arrays it would be better to use the built in sort() function.

  2. BraveBrain Says:

    Seems I typed a lot of formatting spaces for nothing ;)

    and
    [1]=> array(2){
    should be
    [1]=> array(3){

Leave a Reply