Name

ksort()

Synopsis

    bool ksort ( array &arr [, int options] )

The ksort() function takes an array as its only parameter, and sorts it by its keys while preserving the values. For example:

    $capitalcities['England'] = 'London';
    $capitalcities['Wales'] = 'Cardiff';
    $capitalcities['Scotland'] = 'Edinburgh';
    ksort($capitalcities);
    // sorted by key, so England, Scotland, then Wales

Note that ksort() works by reference, directly changing the value you pass in. The return value is either true or false, depending on whether the sorting was successful.

By default, the sort functions sort so that 2 comes before 10. While this might be obvious, consider how a string sort would compare 2 and 10—it would work character by character, which means it would compare 2 against 1 and, therefore, put 10 before 2. Sometimes this is the desired behavior, so you can pass a second parameter to the sort functions to specify how you want the values sorted, like this:

    $array["1"] = "someval1";
    $array["2"] = "someval2";
    $array["3"] = "someval3";
    $array["10"] = "someval4";
    $array["100"] = "someval5";
    $array["20"] = "someval6";
    $array["200"] = "someval7";
    $array["30"] = "someval8";
    $array["300"] = "someval9";
    var_dump($array);
    ksort($array, SORT_STRING);
    var_dump($array);

If you want to force a strictly numeric sort, you can pass SORT_NUMERIC as the second parameter.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.