Computer >> Computer tutorials >  >> Programming >> PHP

ksort() function in PHP


The ksort() function sorts an array by key in ascending order. It returns TRUE on success or FALSE on failure.

Syntax

ksort(arr, flag)

Parameters

  • arr − The array to sort.

  • flag

    • 0 = SORT_REGULAR − Default. Compare items normally. Do not change 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.

Return

The ksort() function returns TRUE on success or FALSE on failure.

Example

The following is an example

<?php
$product = array("headphone"=>"10", "mouse"=>"24", "pendrive"=>"13");
ksort($product);
foreach ($product as $key => $val) {
   echo "$key = $val\n";
}
?>

Output

headphone = 10
mouse = 24
pendrive = 13