Home Tutorial Php Phpbasics PHP Key Sorting

 
 

PHP Key Sorting
Posted on: October 22, 2009 at 12:00 AM
Advertisement
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);

?>

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 )

Advertisement

Related Tags for PHP Key Sorting:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 22, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com