Tuesday, June 23, 2009

Different Array Sorting Functions


We all are familiar with arrays. But PHP provides lot of array functions. Those functions help us to reduce code length and save time. Here I am trying to point out some of the useful array sorting functions.

sort

To sort an array

Syntax : sort($array,$flags)
sort functiom has four flags.They are :
SORT_REGULAR - compare items normally
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale

eg :

$arr = array( 35, 40, 20, 14, 36);
sort($arr);
foreach ($arr as $key => $val) {
echo "arr[" . $key . "] = " . $val . "\n";
}

You will get following Output

arr[0] = 14 arr[1] = 20 arr[2] = 35 arr[3] = 36 arr[4] = 40


rsort

rsort function sorts an array in reverse order. This function is just opposite of sort function.

eg :
$arr = array( 35, 40, 20, 14, 36);
rsort($arr);
foreach ($arr as $key => $val) {
echo "arr[" . $key . "] = " . $val . "\n";
}
You will get following Output
arr[0] = 40 arr[1] = 36 arr[2] = 35 arr[3] = 20 arr[4] = 14


asort

asort function is similar to sort function. The only difference is it will not change the array index.

eg :

$arr = array( 35, 40, 20, 14, 36);
asort($arr);
foreach ($arr as $key => $val) {
echo "arr[" . $key . "] = " . $val . "\n";
}

You will get following Output

arr[3] = 14 arr[2] = 20 arr[0] = 35 arr[4] = 36 arr[1] = 40


arsort

arsort function is similar to rsort function. The only difference is it will not
change the array index.

eg :

$arr = array( 35, 40, 20, 14, 36);
arsort($arr);
foreach ($arr as $key => $val) {
echo "arr[" . $key . "] = " . $val . "\n";
}

You will get following Output

arr[1] = 40 arr[4] = 36 arr[0] = 35 arr[2] = 20 arr[3] = 14


ksort

ksort function will sort an array by key.

eg :

$arr = array( 35, 40, 20, 14, 36);
ksort($arr);
foreach ($arr as $key => $val) {
echo "arr[" . $key . "] = " . $val . "\n";
}

You will get following Output

arr[0] = 35 arr[1] = 40 arr[2] = 20 arr[3] = 14 arr[4] = 36


krsort

krsort function will sort an array by key in reverse order.

eg :

$arr = array( 35, 40, 20, 14, 36);
krsort($arr);
foreach ($arr as $key => $val) {
echo "arr[" . $key . "] = " . $val . "\n";
}

You will get following Output

arr[4] = 36 arr[3] = 14 arr[2] = 20 arr[1] = 40 arr[0] = 35