views:

334

answers:

3

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.

+5  A: 

See

KennyTM
Nice collection..
NAVEED
+3  A: 

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] => answers
     [2] => programming
     [3] => question
     [4] => Stackoverflow
}

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.

Anthony
A: 

Please try to run this:

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

sort($values);

You will see that you are wrong.

ion