1

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);
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Ahmad
  • 2,099
  • 10
  • 42
  • 79
  • What you have tried so far? Please add your code efforts – Alive to die - Anant Sep 22 '22 at 12:43
  • is it necessary to use default sort functions, because I don't think you will get default functions to help your case here – Saad Rehman Sep 22 '22 at 12:44
  • I tried with the php `sort` function and `asort` `asort($array, SORT_STRING);` – Ahmad Sep 22 '22 at 12:44
  • 1
    you can use usort() and a preg_split – soma Sep 22 '22 at 12:45
  • 1
    '3110 - with a string', 128 => '3009 - keep a string', 126 => '3111 - a string', 121 => '3114 - be a string', 122 => '3113 - last string', ]; function cmp($a, $b) { $text1 = preg_split("/- /", "$a"); $text2 = preg_split("/- /", "$b"); return strcmp( $text1[1], $text2[1]); } usort($array, "cmp"); var_export($array); – soma Sep 22 '22 at 12:55

1 Answers1

0

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98