Compare two strings in a case-sensitive manner The Strcmp() function performs a binary-safe comparison of two strings, case-sensitively. Its form is:
int strcmp (string str1, string str2)
One of the following possible values will be returned based on the comparison result.
•Return 0 if str1 and str2 are equal.
•If str1 is less than str2, return -1.
•If str1 is greater than str2, return 1.
Websites often require the user to be registered to enter and confirm his chosen password, reducing the possibility of generating an incorrect password due to typing errors. Because passwords are usually case-sensitive, strcmp() is very suitable for comparing these two passwords:
Copy code The code is as follows:
$pswd = "supersecret";
$pswd2 = "supersecret";
if (strcmp($pswd,$pswd2) != 0)
echo "Your passwords do not match!";
else
echo "Passwords match!";
?>
Note that for strcmp (), the strings must match exactly to be considered equal. For example, Supersecret is different from supersecret. If you want to compare two strings in a case-insensitive manner, consider strcasecmp () described below.
Another confusing point about this function is that it returns 0 when the two strings are equal. This is different from using the == operator to complete string comparison, as follows:
if ( $str1 == $str2)
Both methods have the same goal, they are to compare two strings, but remember that they return The value is different.
Example code:
Copy code The code is as follows:
echo strcmp("Hello world!","Hello world!");
//Return 0
?>
The following is a better strcmp example code:
PHP strcmp code to control access based on IP address
Simple addition:
The comparison between str1 and str2 here is actually a comparison of the ASCII values of str1 and str2
For example:
strcmp ("A", "a"); The return value is -1
// The ASCII value of a is 97 The ASCII value of A is 65
From this example, we can also see that when strcmp() is used to compare strings, the difference is Upper and lower case
Let’s look at the in-depth understanding of strcmp:
strcmp("abc","abc"); At this time, the return value of string equality is 0
Let’s change strcmp("aBc","abc"); at this time If they are not equal, the return value is -1
Since strcmp compares aBc and abc one by one, the first of the two strings is compared with the first, the
2nd is compared with the second... When each comparison Only when the ASCII values of are equal can the comparison continue with the next pair of
characters. Therefore, if the second pair B and b are compared and they are not equal, then the comparison stops and a return value appears.
if ("abc">"aBC") The comparison principle is the same
The above introduces the strcmp php strcmp usage instructions, including strcmp content. I hope it will be helpful to friends who are interested in PHP tutorials.