phparrayssortingprefixcustom-sort

Custom sort a flat array with priority given to values starting with an input string


I have array and contains 50 values ,

example

[
    'london',
    'bluehit',
    'green',
    'lonpark',
    'abc',
    'aab',
    'lonsee',
]

I want to sort with preference given to values starting with a provided string, then traditional alphabetical sorting.

If I give an argument as lon then my array should be sorted as:

[
    'london',
    'lonpark',
    'lonsee',
    'aab',
    'abc',
    'blurhit',
    'green',
]

Solution

    1. replace the string in question with a character with code 1
    2. sort normally
    3. replace the character back

    this is it ;)

     $str = "lon";
     $a = array('london', 'bluehit', 'green', 'lonpark', 'abc', 'aab', 'lonsee');
     $b = preg_replace("~^$str~", "\x01", $a);
     sort($b);
     $b = preg_replace('~\x01~', "lon", $b);
     print_r($b);
    

    upd: even simpler is to prepend the string with "\x01" rather than replacing it. This also allows for case-insensitive matching or to match a set of strings:

     $str = "lon";
     $a = array('london', 'bluehit', 'green', 'Lonpark', 'abc', 'aab', 'lonsee');
     $b = preg_replace("~^$str~i", "\x01$0", $a);
     sort($b);
     $b = str_replace('~\x01~', "", $b);
     print_r($b);