PHP: How to sort values of an array in alphabetical order?


Question

I want to sort values of an array in alphabetical order in PHP. If all values started with same character then they should be sorted using second character and so on. Ignore case sensitive.

For Example:

before:
values[0] = "programming";
values[1] = "Stackoverflow";
values[2] = "question";
values[3] = "answers";
values[4] = "AA Systems";

after:
values[0] = "AA Systems";
values[1] = "answers";
values[2] = "programming";
values[3] = "question";
values[4] = "Stackoverflow";

I have found some algorithms but I want a way that is fast and with small number of statements. Ignoring case sensitive is special for me. Thanks.

1
10
1/19/2010 6:45:23 PM

Accepted Answer

See

14
1/17/2010 7:30:54 AM

Your example makes two assumptions:

  1. That you are only dealing with simple, 1-dimensional arrays.

  2. That after sorting alphabetically, your index will update so that the first element alphabetically will be assigned key 0 and so forth.

Given those parameters, your simplest solution is to use the array method sort(). With your example:

$values[0] = "programming";
$values[1] = "Stackoverflow";
$values[2] = "question";
$values[3] = "answers";
$values[4] = "AA Systems";

sort($values);

Which will result in the following:

Array {
     [0] => AA Systems
     [1] => Stackoverflow
     [2] => answers
     [3] => programming
     [4] => question
}

There are other array sorting functions that might be a better fit. For instance, the simple one I use above puts upper-case in front of lower-case, so if you had "security" as an item (all lower-case) it would go after "Stackoverflow" since the upper-case s would take precedence over se vs. st. To sort without case-sensitivity, you could use natcasesort(), which would produce the following with the given array:

Array {
     [0] => AA Systems
     [1] => answers
     [2] => programming
     [3] => question
     [4] => Stackoverflow
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon