72

What the title says. Specifically if I have

$array1['name'] = 'zoo';
$array2['name'] = 'fox';

How can I determine that alphabetically $array2's name should come above $array1's?

1

5 Answers 5

114

Use strcmp. If the first argument to strcmp is lexicographically smaller to the second, then the value returned will be negative. If both are equal, then it will return 0. And if the first is lexicograpically greater than the second then a positive number will be returned.

nb. You probably want to use strcasecmp(string1,string2), which ignores case...

0
15

You can compare both strings with strcmp:

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

11

I'm a little late (then again I wasn't a programmer yet in 2009 :-) No one mentioned this yet, but you can simply use the operators which you use on number as well.

< > <= >= == != and more

For example:

'a' > 'b' returns false

'a' < 'b' returns true

http://php.net/manual/en/language.operators.comparison.php

IMPORTANT

There is a flaw, which you can find in the comments below.

3
  • 1
    Man, this is definitely the best answer for this thread and it didn't have a single upvote! If you only need to compare two strings to simply find the one which comes first in alphabetical order, it is definitely the lighter, most clever solution. Yet, so stupid it almost hurts. Commented Aug 30, 2017 at 0:42
  • 1
    @MarcosBuarque: I appreciate it. I was just 8 years too late with my answer :-)
    – JMRC
    Commented Sep 5, 2017 at 17:11
  • 9
    This does not work as expected. For example '10' < '2' evaluates to false even though the string '10' should come before '2' if you compare alphabetically (which is what the question is about). This is because whenever strings look like integers PHP automatically converts them to integers and compares them numerically instead of alphabetically. You should go with strcmp() as suggested if your goal is to really compare alphabetically.
    – jlh
    Commented Oct 26, 2018 at 15:37
2

I often use natsort (Natural Sort), since I usually just want to preserve the array for later use anyway.

Example:

natsort($unsorted_array);

var_dump($usorted_array); // will now be sorted.
1

sort

EDIT just realised values from different arrays, could array_merge first but not sure thats what you want

Not the answer you're looking for? Browse other questions tagged or ask your own question.