PHP Key Sorting


 

PHP Key Sorting

PHP Key Sorting: In PHP you can sort the values of an array as well as keys, this tutorial is all about how to sort the keys of an array.

PHP Key Sorting: In PHP you can sort the values of an array as well as keys, this tutorial is all about how to sort the keys of an array.

PHP Sort Array by Key

In PHP there are are so many built in functions are available which make this language easier. In general we sort the values of an array, but sometimes we need to sort the keys instead of values, PHP provided us three functions to sort any array by  key. These are:

i)    ksort()

ii)    krsort()

Now we will discuss these functions one by one in detail:

i)    ksort(): This function sorts an array by key maintaining the correlation with the value, this function is useful for associative array.

General Format bool ksort(array $array [,int $sort_flags=SORT_REGULAR] )
Return Value True/False
Parameters array: the input array sort_flags:
  • sort_regular: normal comparison
  • sort_numeric: numeric comparison
  • sort_string: string comparison

 

Example 1:

<?php

$array=array(30=>"twitter",11=>"orkut",7=>"facebook");

echo"<b>Before sorting the keys of the array is:</b><br/>";

print_r($array);

ksort($array);

echo"<br/><b>Before sorting the keys of the array is:</b><br/>";

print_r($array);

?>

Output:

Before sorting the keys of the array is:
Array ( [30] => twitter [11] => orkut [7] => facebook )
After sorting the keys of the array is:
Array ( [7] => facebook [11] => orkut [30] => twitter )

From the above example we can see that the sorting is done on the key instead of value.

ii)    krsort(): This function sorts an array by key in reverse order maintaining the correlation with the value, this function is useful for associative array.

General Format bool krsort(array $array [,int $sort_flags=SORT_REGULAR] )
Return Value True/False
Parameters array: the input array sort_flags:
  • sort_regular: normal comparison
  • sort_numeric: numeric comparison
  • sort_string: string comparison

 

Example 2:

<?php

$array=array(30=>"twitter",11=>"orkut",7=>"facebook");

echo"<b>Before sorting the keys of the array is:</b><br/>";

print_r($array);

krsort($array);

echo"<br/><b>After sorting the keys in reverse order:</b><br/>";

print_r($array);

?>

0

Output:

Before sorting the keys of the array is:
Array ( [30] => twitter [11] => orkut [7] => facebook )
After sorting the keys in reverse order:
Array ( [30] => twitter [11] => orkut [7] => facebook )

Ads