PHP ksort() Function
In this chapter you will learn:
- Definition for PHP ksort() Function
- Syntax for PHP ksort() Function
- Parameter for PHP ksort() Function
- Note for PHP ksort() Function
- Example - Pass a second parameter to the sort functions to specify how you want the values sorted
- Example - Sort an associative array in ascending order, according to the key
Definition
The ksort()
function takes an array and sorts it by its keys while preserving the values.
Syntax
PHP ksort() Function has the following syntax.
bool ksort ( array &arr [, int options] )
Parameter
Parameter | Is Required | Description |
---|---|---|
array | Required. | Specifies the array to sort |
sortingtype | Optional. | Specifies how to compare the array elements/items. |
Possible values for sortingtype:
Value | Description |
---|---|
0 = SORT_REGULAR | Default. Compare items normally without changing types |
1 = SORT_NUMERIC | Compare items numerically |
2 = SORT_STRING | Compare items as strings |
3 = SORT_LOCALE_STRING | Compare items as strings, based on current locale |
4 = SORT_NATURAL | Compare items as strings using natural ordering |
5 = SORT_FLAG_CASE | an be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively |
Note
Use the krsort() function to sort an associative array in descending order, according to the key.
Use the asort() function to sort an associative array in ascending order, according to the value.
<?PHP//from j a v a2 s.c o m
$capitalcities['A'] = 'Z';
$capitalcities['B'] = 'X';
$capitalcities['C'] = 'Y';
ksort($capitalcities);
print_r($capitalcities);
?>
ksort()
works by reference, directly changing the array.
The return value is either true or false, depending on whether the sorting was successful.
The code above generates the following result.
Example 1
We can pass a second parameter to the sort functions to specify how you want the values sorted, like this:
<?PHP/* ja va 2 s . com*/
$array["1"] = "1";
$array["2"] = "2";
$array["3"] = "3";
$array["10"] = "10";
$array["100"] = "100";
var_dump($array);
ksort($array, SORT_STRING);
var_dump($array);
?>
If you want to force a strictly numeric sort, you can pass SORT_NUMERIC
as the second
parameter.
The code above generates the following result.
Example 2
Sort an associative array in ascending order, according to the key:
<?php
$age=array("PHP"=>"5","Java"=>"7","java2s.com"=>"3");
ksort($age);
?>
Next chapter...
What you will learn in the next chapter:
- Definition for PHP list() Function
- Syntax for PHP list() Function
- Parameter for PHP list() Function
- Note for PHP list() Function
- Example - Assign value in an array to a list of variables
- Example - Using the first and third variables
- Example - Compare the code with and without list() function
- Example - Use list during array loop