1

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?

4
  • 7
    Read the documentation and pay close attention to the sort flags, or have a look at natsort(). Commented Jun 21, 2015 at 17:45
  • are you trying to sort just on basis on alphabets and ignoring the numeric values in the string? Commented Jun 21, 2015 at 17:47
  • thanks for a quick guidance. Commented Jun 21, 2015 at 17:48
  • 1
    No, alphabet will remain the same in the array, i have to sort array on the basis of numbers as described above in the question Commented Jun 21, 2015 at 17:51

1 Answer 1

1
$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];
Sign up to request clarification or add additional context in comments.

3 Comments

in my case natsort() is not working as i have multidimesional array: array( 'BFIMO1' => array( 'Equipment' => array( 'equipID' => 'BFIMO1', 'NAME' => '3000A Main Breaker- 277/480v Main', 'location' => 'Basement- SwGear Room', 'comments' => '3000A Main Breaker- 277/480v Main', 'PPE' => null ) ), 'BFIMO10' => array( 'Equipment' => array( 'equipID' => 'BFIMO10', 'NAME' => 'Chiller Pump', 'location' => 'Basement- SwGear Room', 'comments' => 'Chiller Pump', 'PPE' => null ) ), I am getting Array to string conversion error
do you want to sort this keys 'BFIMO1' ?
yes i have keys BFIMO1 BFIMO10 BFIMO2 and so on . I want to sort these in accending order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.