Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

ksort

Sorts an array by key.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe array being sorted.
$flagsintOptional. The comparison mode.

Return value

trueAlways `true`; the array itself is modified.

Examples

Keys in alphabetical order:

<?php
 
$stock = ['pear' => 5, 'apple' => 12, 'plum' => 3];
 
ksort($stock);
 
echo implode(', ', array_keys($stock));

Output:

apple, pear, plum

In reverse order — krsort():

<?php
 
$years = [2023 => 'a', 2025 => 'c', 2024 => 'b'];
 
krsort($years);
 
echo implode(', ', array_keys($years));

Output:

2025, 2024, 2023

Notes

The values stay attached to their keys.

See also

  • asort — Sorts an array by value, keeping the keys.
  • sort — Sorts an array in ascending order.

Related recipes

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.