Home >Backend Development >PHP Problem >What are the ways to compare strings for equality in PHP?
The methods for PHP to compare whether strings are equal are: 1. Use the "String 1==String 2" statement; 2. Use the "String 1=== String 2" statement; 3. Use "strcmp (string 1, string 2)" statement; 4. Use the "strcasecmp (string 1, string 2)" statement and so on.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Compare two characters Check whether strings are equal
Generally, you can use != and == to compare whether two objects are equal. The reason why they are two objects is because they are not necessarily all strings. You can also For integers and so on. For example
$a = "joe"; $b = "jerry"; if ($a != $b) { echo "不相等"; } else { echo "相等"; }
If you use !==, === (you can see an extra equal sign) for comparison, the types of the two objects must be strictly equal to return true; otherwise, use ==, != The string will be automatically converted into the corresponding type for comparison.
22 == "22"; // 返回 true 22 === "22"; // 返回false
Because of this, some unexpected "accidents" often occur in our program:
0 == "我爱你"; // 返回true 1 == "1 我爱你";// 返回true
php tutorial There is also a set of functions for string comparison: strcmp, strcasecmp, strncasecmp(), strncmp(), return value description:
strcmp is used for case-sensitive (i.e. case-sensitive) string comparison:
echo strcmp("abcdd", "abcde"); // 返回 1 (>0), 比较的是 "b"和"b"
strcasecmp is used For case-insensitive string comparison:
echo strcasecmp("abcdd", "abcde"); // 返回 -1 (<0), 比较的是"d"和"e"
strncmp is used to compare part of the string, starting from the beginning of the string. The third parameter is the length to be compared:
echo strncmp("abcdd", "abcde", 3); // 返回 1 (>0), 比较了 abc 和 abc
strncasecmp is used to compare part of a string in a case-insensitive manner. The comparison starts from the beginning of the string. The third parameter is the length to be compared:
echo strncasecmp("abcdd", "abcde", 3); // 返回 0, 比较了 abc 和 abc, 由于不区分大小写,所以两者是相同的。
Another situation is to compare characters alone. The string size cannot meet our predetermined needs. For example, as usual, 10.gif will be better than 5.gif. Large, but if you apply the above functions, -1 will be returned, which means 10.gif than 5.gif. For this situation, PHP provides two naturally contrasting functions strnatcmp and strnatcasecmp:
echo strnatcmp("10.gif", "5.gif"); // 返回 1 (>0) echo strnatcasecmp("10.gif", "5.gif"); // 返回 1 (>0)
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What are the ways to compare strings for equality in PHP?. For more information, please follow other related articles on the PHP Chinese website!