Sorting elements in array with a certain condition
How can I make the function look better?


One alternative approach to the switch statement inside get_sort_by_key() is to define a lookup-table using an array: 

define('KEY_MAPPING',array('lng','topic','page','sort','search'));


(or it could be a constant defined on a class if such a relevant class exists).

Then the code block in the foreach can be simplified using array_search() to see if a corresponding index is returned. If not (i.e. it returned false) then use 5 as the fallback value. 

foreach ($array as $key =&gt; $value) {
    $key = strtolower(trim($key));
    $order = array_search($key, KEY_MAPPING);
    if ($order === false) {
        $order = 5;
    }
    $new_array[$order][$key] = $value;
 }


See this playground example for a demonstration.

For small lists of parameters like this the time difference won't be much. I found this SO question from 6 years ago (and the results may have changed since Ariel's answer as PHP internals have changed but likely not by much).

I tried to find some online posts comparing switch statements with array lookups. The first couple results I see in Google are 6-9 years old:


TechnoSophos: Microbenchmarking PHP: Switch Statements are Slow
DevShed: PHP: The Switch Statement and Arrays ("can they not indent??")
ExceptionsHub: In PHP what's faster, big Switch statement, or Array key lookup


The general consensus is that the array lookup is faster. And typically it can require fewer lines of code. There is a quote somebody said (I can't remember who, so if you know who to give credit please let me know): "The easiest line to debug is the line you didn't write".