Content · Programming · PHP

PHP ksort() Function: Usage and Examples

Learn ksort() with clear PHP examples, output, practical scenarios, important behaviors, and common beginner mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

PHP developers sometimes need to sort an associative array by keys in ascending order. This comes up when preparing data, displaying results, or integrating information with other services.

The ksort() operation handles this particular task. The following examples show its result, its limitations, and a practical way to apply it.

What Is ksort() in PHP?

Sort an associative array by keys in ascending order.

Its syntax is:

ksort(array &$array, int $flags = SORT_REGULAR): true

The syntax shows the expected parameters and return type. Arguments marked with an ampersand are passed by reference and may be modified. Optional parameters control additional behavior; values must match the declared types.

Important: The operation changes the input in place but keeps each value attached to its key.

Parameters:

  • &$array — May be updated by the function.
  • $flags — A named input or configuration argument; use the declared type and optional default shown above.

Example 1: Basic Usage

This first example uses a small input to demonstrate the main result of ksort().

<?php

$prices = ["pear" => 2, "apple" => 3]; ksort($prices); print_r($prices);

Output:

Array
(
    [apple] => 3
    [pear] => 2
)

The output demonstrates the primary operation: sort an associative array by keys in ascending order.

Example 2: Understanding Another Case

This second example changes the input or option to reveal a different behavior of ksort().

<?php

$items = [10 => "ten", 2 => "two"]; ksort($items, SORT_NUMERIC); print_r($items);

Output:

Array
(
    [2] => two
    [10] => ten
)

Compared with the first example, this one illustrates the same operation with a different input shape or option. The operation changes the input in place but keeps each value attached to its key.

Practical Example: A Real Application Scenario

Here is a practical use of ksort() with realistic sample information. Adapt the values to match your application.

<?php

$headings = ["zebra" => "Z", "alpha" => "A", "middle" => "M"]; ksort($headings); foreach ($headings as $heading => $label) { echo "$heading: $label\n"; }

Output:

alpha: A
middle: M
zebra: Z

This is a useful starting point, but production code should check errors and validate values before performing the operation. The operation changes the input in place but keeps each value attached to its key.

Important Behavior and Edge Cases

The operation changes the input in place but keeps each value attached to its key.

  • Input: Use the expected PHP types and validate user-provided values.
  • Result: Check the return value separately from any modifications to the input.
  • Environment: For extension, database, or filesystem examples, verify availability and handle failures before accessing results.

Comparison With Related Functions

Function or ApproachWhen to Use It
ksort()Sort an associative array by keys in ascending order.
Related functionskrsort() orders keys descending; asort() sorts by values.

Common Beginner Mistakes

MistakeCorrect Approach
Expecting a sorted copy without changing the inputThese sort functions modify the array directly; copy it first if you need the original.
Using the wrong sort targetDecide whether to sort keys or values, and whether key associations must remain intact.
Assuming every comparison handles text in the same waykrsort() orders keys descending; asort() sorts by values.

Key Takeaways

  • ksort() lets you sort an associative array by keys in ascending order.
  • The operation changes the input in place but keeps each value attached to its key.
  • krsort() orders keys descending; asort() sorts by values.
  • Check input, return values, and environmental requirements when adapting the examples.

ksort() provides a focused PHP operation for sort an associative array by keys in ascending order. Start with the simple examples, then adapt the practical example with the correct checks for your project.

Share this resourceSend this page to someone who may find it useful.