0

How PHP asort() works? What algorithm is used for sorting? I am using asort() function to sort an $array but its not sorting as i wanted.

<?php
  $array = array("test","Travel","en");
  asort($array);
  var_dump($array); "test" }
?>

The var_dump() gives

array(3) { 
    [1] => string(6) "Travel" 
    [2] => string(2) "en" 
    [0] => string(4) "test" 
}
2
  • The algorithm used is a quicksort: see the Note in the PHP Docs... and it's case-sensitive by default, so that's why Travel with an upper-case T comes before en with a lower-case e Commented Jan 12, 2017 at 17:20
  • The manual tells you what sorting algorithm is applied. Commented Jan 12, 2017 at 17:25

3 Answers 3

2

Use flags to change the case sensitivity of the asort() function.

$array = ["test", "Travel", "en"];
asort($array, SORT_FLAG_CASE | SORT_NATURAL);
var_dump($array);

These are documented with the sort() function.

Sign up to request clarification or add additional context in comments.

Comments

1

you can try if natcasesort(case insensitive) you want to sort in natural order:

<?php
  $array = array("test","Travel","en");
  natcasesort ($array);
  var_dump($array);

DEMO HERE & Info here

Comments

0

Firstly, PHP uses an implementation of Quicksort
Secondly, For more information go through http://php.net/sort

Note: agree with @miken32 answer

Comments

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.