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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using ksort() to Sort Arrays by Key in PHP

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
";
}
?>

Output:

a = orange
b = banana
c = apple
d = lemon
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendprogrammingPHPArraySortingksort
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.