Search code examples
phparrayssortingarraylistquicksort

How to sort an array alphabetically if integers are concatenated with array values?


I have an array like this

$array = [
  125 => '3110 - with a string',
  128 => '3009 - keep a string',
  126 => '3111 - a string',
  121 => '3114 - be a string',
  122 => '3113 - last string',
]

Is there any way to use the PHP default sort functions to sort this array alphabetically and ignoring the concatenated integer values?

The result should be

[
  126 => '3111 - a string',
  121 => '3114 - be a string',
  128 => '3009 - keep a string',
  122 => '3113 - last string',
  125 => '3110 - with a string', 
]

I tried with sort and asort functions but it did not help.

asort($array, SORT_STRING);

Solution

  • You can use usort() along with strcmp()

    function cmp($a, $b)
    {
        
        return strcmp(trim(explode('-',$a)[1]) ,trim(explode('-',$b)[1]));
    }
    
    
    usort($array, "cmp");
    
    print_r($array);
    

    https://3v4l.org/NEdmt

    Assumption : I assume that each values of array always contain digit - string format