PHP Sort Varchar Data Array In Ascending Order

524 views Asked by At

I want to sort an array of varchar data in ascending order through PHP code.
I have tried doing it, the result I am getting is :

ABC1
ABC10
ABC11
ABC11A
ABC11B
ABC2
ABC2A
ABC20
ABC3

But i want :

ABC1
ABC2
ABC2A
ABC3
ABC10
ABC11
ABC11A
ABC11B
ABC20

Is there any way to achieve this?

1

There are 1 answers

3
splash58 On BEST ANSWER
$myarray= array("ABC1","ABC10","ABC11","ABC11A","ABC11B","ABC2","ABC2A","ABC20","ABC3");

 natsort($myarray);
 var_dump($myarray);

result

array(9) {
  [0]=>
  string(4) "ABC1"
  [5]=>
  string(4) "ABC2"
  [6]=>
  string(5) "ABC2A"
  [8]=>
  string(4) "ABC3"
  [1]=>
  string(5) "ABC10"
  [2]=>
  string(5) "ABC11"
  [3]=>
  string(6) "ABC11A"
  [4]=>
  string(6) "ABC11B"
  [7]=>
  string(5) "ABC20"
}

UPDATE due to discussion in comments

$keys = array_keys($myarray);
natsort($keys);
$newarray = array();
foreach ($keys as $k) $newarray[] = $myarray[$k];