Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page