Skip to content

There should be only one general sort functionΒ #17271

@nbro

Description

@nbro

Description

I find it unnecessary to have a second sort function just to sort in descending order when we could very well just have an additional parameter that controls this (e.g. sort vs rsort).

Not only this, but I claim that there should be just one general sort function, which allows us

  • to provide a comparison function (i.e. usort, ursort, etc. are unnecessary)
  • allows us to control whether we should maintain the indices/keys or not
  • should allow us to sort by key or value (or both)
  • allows us to sort using the natural algorithm (actually, if we pass SORT_NATURAL to sort it already should be equivalent to natsort, which is thus unnecessary and imo should be deprecated)

In other words, I feel that sort could be extended to actually be able to do anything that all other sort functions do.

The only functions we might still want to keep are array_multisort() and shuffle(), but I'd also say that why shouldn't the general sort function also be able to sort multi-dimensional arrays?

By separating the functions, like we have now, we probably can gain a marginal speed-up, because we avoid some conditional branches, but I'm also not saying that we should maybe completely remove the standalone functions, maybe just eventually deprecated them. The problem is that we need to memorise a lot of functions. You could argue that, if we merge the functions, the general sort function would also become more complicated, but I still think it's better that we just check the documentation of a single function than looking for the documentation of multiple simpler sort functions.

I'd also recommend that there should be a second function, like sortn or sorted, which doesn't sort in place, similar to Python's sorted vs sort. I think something like this was already proposed or at least I think I found an RFC that talked about how the return values of these sort functions are a bit useless. I am not saying that if you sort in-place you should actually return the array (so I am not sure I agree with that RFC), because that's unnecessary, but that there should be a new sort function that sorts not-in-place and actually returns a new array without touching the original (e.g. it uses merge sort instead of quick sort).

This should not be difficult to implement because we should just need to adapt the single functions and put their code into the general one or something like that. The only concern is that we need to make sure we don't break any code, but we should be able to do that easily with reasonable default values for the new additional parameters, such that the current default sort behaviour remains the same.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions