Closed remco-pc closed 4 months ago
Isn't this just array_values with extra steps?
I need todo array_values after the ksort, this could be in the ksort function to speed up
Do your arrays even need sorting? Because your example already is...
Adding a flag that only makes sense to some of the sorting functions but not others is unusual, so I'm looking at what your alternatives are.
What about array_multisort, which can sort by the keys and also renumber the array?
array_multisort(array_keys($array), SORT_NATURAL, $array);
this could be in the ksort function to speed up
That's not necessarily going to be true. ksort() won't know what element should be at [0]
until it's finished sorting the entire array. So how does sorting-with-reindexing work, like regular sort()? By the looks of it, at the end of the sorting, it does something very similar to what array_values does: create a new array and copy the items into it. Thus I would expect the performance of ksort-with-renumbering and ksort+array_values to be about the same.
There's also something to be said about the simplicity of seeing both ksort and array_values explicitly written out and called in code, instead of that behavior being controlled by a special flag that adds (yet another) nuanced sorting behavior to these functions, but that's a different conversation.
Do you still feel that ksort, and I assume the other key-based and associative sorting functions as well, should have a "sort with reindexing" flag?
I though it could speed up, if that isn't the case, ok. I use hardcoded array keys to solve a big where, which need to start at zero, then 1, then 2, then the rest. I will use array_values which should be fast for small arrays.
I didnt know about the multisort, will look into it, but probably is the same speed.
Description
can there be an extra sort flag for re-indexing the array starting from zero & up
ksort($array, SORT_NATURAL);