Understanding PHP strcmp() Function: Syntax, Parameters, Return Values, and Examples
This article explains PHP's strcmp() function, detailing its syntax, parameters, return values based on ASCII comparison, and provides three practical code examples demonstrating how to compare strings for equality, less‑than, and greater‑than relationships.
strcmp() is a PHP string comparison function that determines the relative order of two strings by comparing their ASCII values.
In PHP, string comparison is performed character by character using each character's ASCII code to decide which string is larger, smaller, or if they are equal.
strcmp() Function Syntax
<code>strcmp(string $str1, string $str2): int</code>Parameters $str1 and $str2 represent the two strings to compare. The function returns an integer indicating the relationship between the strings.
If the return value is 0 , $str1 and $str2 are equal.
If the return value is less than 0 , $str1 is less than $str2 .
If the return value is greater than 0 , $str1 is greater than $str2 .
Examples of Using strcmp()
Example 1
<code>$str1 = "apple";
$str2 = "banana";
$result = strcmp($str1, $str2);
if ($result == 0) {
echo "两个字符串相等";
} elseif ($result < 0) {
echo "$str1 小于 $str2";
} else {
echo "$str1 大于 $str2";
}
</code>Output: apple 小于 banana
Example 2
<code>$str1 = "apple";
$str2 = "apple";
$result = strcmp($str1, $str2);
if ($result == 0) {
echo "两个字符串相等";
} elseif ($result < 0) {
echo "$str1 小于 $str2";
} else {
echo "$str1 大于 $str2";
}
</code>Output: 两个字符串相等
Example 3
<code>$str1 = "banana";
$str2 = "apple";
$result = strcmp($str1, $str2);
if ($result == 0) {
echo "两个字符串相等";
} elseif ($result < 0) {
echo "$str1 小于 $str2";
} else {
echo "$str1 大于 $str2";
}
</code>Output: banana 大于 apple
The strcmp() function compares two strings by their ASCII values, returning 0 for equality, a negative number if the first string is smaller, and a positive number if the first string is larger.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.