Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   An Overview Of Sorting Functions in PHP (http://www.go4expert.com/articles/overview-sorting-functions-php-t28459/)

pradeep 28May2012 15:22

An Overview Of Sorting Functions in PHP
 
PHP being the most popular & easy to deploy language for web applications offers a large number for functions for sorting compared to other languages like Perl, Python, etc which hardly have a few basic functions which have to be extended by the programmer.

PHP reduces coding time by providing in-built variety sorting functions, some functions sort associative arrays by keys, some by values & also maintain the key-value relationship. Some functions offer different sorting order like, numeric, alphanumeric, natural, case sensitive etc. The functions we'll be discussing in this article work on the input array itself and does not return a sorted array, they return true on success & false on failure.

Function sort



This is the basic function it sorts items in ascending order & is case sensitive by default though the behaviour can be modified by passing the relevant sort flag. See the sample code below to understand the behaviuor of the function.

Code: PHP

<?php

$languages = array(
    "PHP",
    "ASP.Net",
    "VB.Net",
    "Python",
    "C++"
);

sort($languages);

foreach ($languages as $k => $v) {
    echo "languages[$k] = $v \n";
}

?>


Output:
Code:

languages[0] = ASP.Net
languages[1] = C++
languages[2] = PHP
languages[3] = Python
languages[4] = VB.Net
languages[5] = perl


Function ksort



ksort sorts an array by its keys, and maintains the relationship with the values. This function is helpful for sorting associative arrays.

Code: PHP

<?php

$members = array(
    'kolkata' => 'Pradeep',
    'mumbai' => 'Tanaz',
    'kochi' => 'Anjali',
    'trissur' => 'Shency',
    'hyderabad' => 'Asha'
);

ksort($members);

foreach ($members as $k => $v) {
    echo "$k = $v \n";
}
?>


Output:
Code:

hyderabad = Asha
kochi = Anjali
kolkata = Pradeep
mumbai = Tanaz
trissur = Shency


Function natcasesort



This function has an uncommon algorithm which sorts values in a "human" manner which some call "natural ordering", it also maintains key-value relationship. It's case insensitive. Below is a comparison of the output from normal sorting and natcasesort (Natural Order) sorting. natsort also exists which uses the same algorithm but treats the values in a case sensitive manner.

Code: PHP

<?php
$songs1 = $songs2 = array(
    'SONG1.mp3',
    'song00.mp3',
    'song001.MP3',
    'SONG002.mp3',
    'sOng3.mp3',
    'SonG4.ogg'
);

sort($songs1);

print "Normal sorting\n";
print_r($songs1);

natcasesort($songs2);

print "\nNatural Order sorting\n";
print_r($songs2);
?>


Output:
Code:

Standard sorting
Array
(
    [0] => SONG002.mp3
    [1] => SONG1.mp3
    [2] => SonG4.ogg
    [3] => sOng3.mp3
    [4] => song00.mp3
    [5] => song001.MP3
)

Natural order sorting (case-insensitive)
Array
(
    [1] => song00.mp3
    [2] => song001.MP3
    [3] => SONG002.mp3
    [0] => SONG1.mp3
    [4] => sOng3.mp3
    [5] => SonG4.ogg
)


Function arsort



arsort is just like sort with only difference being is that it sorts in descending order whereas sort sorts in ascending order.

Function uasort



uasort allows a user defined callback function to be passed as parameter which will be used for comparison, check the example below to get a better idea. This function sorts by value. Another sibling of this function is usort the difference being that usort does not preserve key-value relationship. In the code example below we'll see how to sort an array in ascending or descending order depending on the callback function.

Code: PHP

<?php
// function ascending order
function sort_by_temp_asc($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// function descending order
function sort_by_temp_desc($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($b < $a) ? -1 : 1;
}

// Array to be sorted
$temperature = array(
    'Ipswich' => 24,
    'Kolkata' => 38,
    'Darjeeling' => 7,
    'Verkhoyansk' => -40,
    'Chennai' => 42,
    'Siberia' => -70,
    'Siachen' => -15,
    'Kochi' => 32
);

// Sort ascending order and print
uasort($temperature, 'sort_by_temp_asc');
print_r($temperature);

// Sort descending order and print
uasort($temperature, 'sort_by_temp_desc');
print_r($temperature);

?>


Output:
Code:

Array
(
    [Siberia] => -70
    [Verkhoyansk] => -40
    [Siachen] => -15
    [Darjeeling] => 7
    [Ipswich] => 24
    [Kochi] => 32
    [Kolkata] => 38
    [Chennai] => 42
)
Array
(
    [Chennai] => 42
    [Kolkata] => 38
    [Kochi] => 32
    [Ipswich] => 24
    [Darjeeling] => 7
    [Siachen] => -15
    [Verkhoyansk] => -40
    [Siberia] => -70
)


Another sibling of the uasort is uksort it's difference lies in the fact that it passes the keys to the callback function instead of the values.

Function shuffle



This function is technically a sorting function, as it sorts the array items randomly, the randomness is generated by PHP itself.

Code: PHP

<?php
$items = array(
    1,
    3,
    5,
    -1,
    -10,
    'a',
    'v',
    'b'
);

// First time
shuffle($items);

foreach ($items as $item) {
    echo "$item ";
}

echo "\nAgain\n";
shuffle($items);

foreach ($items as $item) {
    echo "$item ";
}


Output:
Code:

a -10 b 1 3 -1 v 5
Again
-1 5 1 -10 b v 3 a


References



http://www.php.net/manual/en/


All times are GMT +5.5. The time now is 13:49.