Skip to content

Instantly share code, notes, and snippets.

@lsloan
Forked from cdzombak/README.md
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsloan/46b4783bd90323136670 to your computer and use it in GitHub Desktop.
Save lsloan/46b4783bd90323136670 to your computer and use it in GitHub Desktop.
Resursive version of PHP's ksort.
See README.md for details.

This is a recursive version of PHP's ksort function.

I tried to make a shorter version of this. What I ended up with isn't necessarily shorter when it's made readable. It becomes a one-liner when the wrapper function is removed and the lines combined:

function ksortRecursive(&$array, $unusedKey, $sortFlags = SORT_REGULAR) {
	return is_array($array) && ksort($array, $sortFlags) && array_walk($array, __FUNCTION__, $sortFlags);
}

Unfortunately, array_walk always passes the index to the callback, even though it's not needed here. In this shorter version, one would need to specify some value for the unused key if a sort flag is to be used.

function ksortRecursive(&$array, $sortFlags = SORT_REGULAR) {
function ksortRecursiveCallback(&$array, $unusedKey, $sortFlags) {
return is_array($array) &&
ksort($array, $sortFlags) &&
array_walk($array, __FUNCTION__, $sortFlags);
}
return ksortRecursiveCallback($array, null, $sortFlags);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment