PHP ksort()Functions

PHP Array ReferenceComplete PHP Array Reference

Examples

Sort an associative array in ascending order by key:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
?>

Run Example »

Definition and Usage

The ksort() function sorts an associative array in ascending order by key.

Tip:Use thekrsort()function to sort an associative array in descending order by key.

Tip:Use theasort()function to sort an associative array in ascending order by value.

Syntax

ksort(array,sortingtype);

Parameters Description
array Required. Specifies the array to sort.
sortingtype Optional. Specifies how to sort the array's elements/items. Possible values:
  • 0 = SORT_REGULAR - Default. Compare items normally (Standard ASCII, 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 the current locale (can besetlocale()changed).
  • 4 = SORT_NATURAL - Compare items as strings, using a similarnatsort()natural ordering.
  • 5 = SORT_FLAG_CASE - Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively.

Technical Details

Return Value: Returns TRUE on success, or FALSE on failure.
PHP Version: 4+


PHP Array ReferenceComplete PHP Array Reference Other Extensions