PHP MySQL tutorial

Sorting Arrays in PHP

One of the most common tasks in PHP is to sort an array according to ascending or descending order. PHP provides several built-in functions to perform such functionality. This article throws light on some of the most commonly used array sorting functions.

sort()

Used to sort a non-associative array in ascending order. If the items are strings, strong is done alphabetically, if items are numbers, items are sorted from smallest to largest.

rsort()

Used to sort a non-associative array in descending order. If the items are strings, sorting is done in reverse alphabetically order, if items are numbers, items are sorted from largest to smallest.

asort()

Sorts an associative array in ascending order on the basis of value. If the values are strings, sorting is done in alphabetically order, if values are numbers, items are sorted from smallest to largest value

ksort()

Sorts an associative array in ascending order on the basis of key. If the keys are strings, sorting is done in alphabetically order, if keys are numeric, items are sorted from smallest largest key

arsort()

Sorts an associative array in descending order on the basis of value. If the values are strings, sorting is done in reverse alphabetically order, if values are numbers, items are sorted from largest to smallest values

krsort()

Sorts an associative array in descending order on the basis of key. If the keys are strings, sorting is done in reverse alphabetically order, if keys are numeric, items are sorted from largest to smallest keys

Have a look at a working example of these functions.

 100,
              'English' => 76,
              'History' => 70,
              'Science' =>89,
              'Geograpy'=>67
                    );

// Using sort function
sort($numarray);
foreach($numarray as $nums) {
    echo $nums;
    echo "
"; } echo "

"; // Using rsort function rsort($stringarray); foreach($stringarray as $strings) { echo $strings; echo "
"; } echo "

"; // using asort function asort($assocarray); foreach($assocarray as $key => $val) { echo $val; echo "
"; } echo "

"; // Using ksort function ksort($assocarray); foreach($assocarray as $key => $val) { echo $key; echo "
"; } echo "

"; // Using arsort function arsort($assocarray); foreach($assocarray as $key => $val) { echo $val; echo "
"; } echo "

"; // Using arsort function krsort($assocarray); foreach($assocarray as $key => $val) { echo $key; echo "
"; } echo "

"; ?>

Download the code
Run the code

<<< XML DOM ParserCommonly Used Array Functions in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .