In a nutshell, I needed to traverse any number of dimensions of a multidimensional array (or not) and I wanted the process to be as predictable as possible (in order to proliferate the pattern throughout a larger body of work). So I came up with this - it feels too easy. Are there any performance sinks using ksort like this that I'm not aware of? Is there a cleaner / more performant way to accomplish this? My goal was to sort (numerically) a vast body of misshapen data groups for the purpose of lets say a tiered score system with nested, associative values which some are arrays of more associative information (think a really complex golf card or something similar).

Is this bad practice? :

function recursive_key_sort(&$by_ref_array)
    ksort($by_ref_array, SORT_NUMERIC );
    foreach ($by_ref_array as $key => $value) {
        if (is_array($value))

didn't see a similar question so I apologize in advance - again my main interest/concern is "this seemed too easy" thanks.

1 Answer 1


After some investigation, I would say this seems pretty optimal. Please see my gist here.

In the PHP file in the gist I've generated some nested arrays with unsorted keys using one function, counted the total number of keys (including keys in nested arrays) using the recursive option to count, timed sorting the array using your function above, generated a flat array with unsorted keys and timed sorting this using ksort.

I've done this for a range of different top-level keys, and each 16 times, taken the average and then run the output data through gnuplot.

You can see from the output graph that your recursive function (purple) is tending towards the ksort of the flat array(blue) to the extent that at greater than 1 million total keys, the recursive sort only takes on average about 1.5x the time of the flat sort for an equivalent number of keys.

Note that this was run on PHP 5.6.10 on ArchLinux, YMMV

  • good deal - thanks for the GIST and your methodology regarding how to rationalize this. Much appreciated. Commented Aug 10, 2015 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.