Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare 2 strings alphabetically in PHP?

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?

like image 808
Ali Avatar asked Oct 20 '09 15:10

Ali


People also ask

How can we compare two strings in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

Can you use == to compare strings in PHP?

The most common way you will see of comparing two strings is simply by using the == operator if the two strings are equal to each other then it returns true. This code will return that the strings match, but what if the strings were not in the same case it will not match.

How do I check if two strings are equal in PHP?

Answer: Use the PHP strcmp() function You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2 ; returns > 0 if str1 is greater than str2 , and 0 if they are equal.

Can you use == to compare two strings?

== operator is avoided, since it checks for reference equality, i.e. if the strings point to the same object or not. The methods mentioned in the article provide a meticulous way to compare two strings in the programming language of java.


3 Answers

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...

like image 166
aviraldg Avatar answered Oct 05 '22 19:10

aviraldg


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.

like image 37
Gumbo Avatar answered Oct 05 '22 20:10

Gumbo


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.

like image 26
JMRC Avatar answered Oct 05 '22 19:10

JMRC