Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

ksort()

Put a map in ascending key order in place for a repeatable traversal.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

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

Put a map in ascending key order in place for a repeatable traversal. SORT_STRING compares text and SORT_NUMERIC compares numbers, giving different orders for keys 10 and 2. Values stay attached and the function returns true. Since PHP 8.2 the default SORT_REGULAR compares the string keys "09" and "010" numerically and puts "09" first. SORT_STRING puts "010" first.

Signature

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

Example output

[[10,2],[2,10]]
[["09","010"],["010","09"]]

Examples

<?php
$rows = [10=>"ten",2=>"two"];
$text = $rows; ksort($text, SORT_STRING);
ksort($rows,SORT_NUMERIC);
echo json_encode([array_keys($text),array_keys($rows)]);
$padded=["09"=>9,"010"=>10]; $lexical=$padded;
ksort($padded); ksort($lexical,SORT_STRING);
echo PHP_EOL,json_encode([array_keys($padded),array_keys($lexical)]);

Result

[[10,2],[2,10]]
[["09","010"],["010","09"]]

Sources