Using ksort() to Sort Arrays by Key in PHP
This article explains the PHP ksort() function, which sorts an associative array by its keys while preserving key‑value relationships, describes its parameters and return values, and provides a complete example with code and expected output.
The ksort() function sorts an array by its keys, maintaining the association between keys and values, and is primarily used for associative arrays in PHP.
Function signature: bool ksort(array &$array [, int $sort_flags = SORT_REGULAR])
Description: The function orders the array according to its keys. The optional $sort_flags parameter can modify the sorting behavior.
Parameters:
array : The input array to be sorted.
sort_flags : Optional flag to change sorting behavior (default SORT_REGULAR ).
Return value: Returns TRUE on success, FALSE on failure.
Example:
<?php
$fruits = array(
"d" => "lemon",
"a" => "orange",
"b" => "banana",
"c" => "apple"
);
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>Output:
a = orange
b = banana
c = apple
d = lemonLaravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.