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?
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().
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.
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.
== 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.
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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With