Backend Development 4 min read

Understanding PHP strcmp() Function: Syntax, Return Values, and Examples

The article explains PHP's strcmp() string comparison function, detailing its ASCII‑based comparison logic, syntax, return values, and provides three practical code examples demonstrating how to determine equality, less‑than, or greater‑than relationships between strings.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP strcmp() Function: Syntax, Return Values, and Examples

strcmp() is a PHP function that compares two strings based on their ASCII values and returns an integer indicating their relative order.

In PHP, string comparison is performed character by character using ASCII codes.

Syntax of strcmp()

strcmp(string $str1, string $str2): int

The parameters $str1 and $str2 are the two strings to compare; the function returns 0 if they are equal, a negative number if $str1 is less than $str2 , and a positive number if $str1 is greater.

If the return value is 0, the strings 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

$str1 = "apple";
$str2 = "banana";
$result = strcmp($str1, $str2);
if ($result == 0) {
    echo "两个字符串相等";
} elseif ($result < 0) {
    echo "$str1 小于 $str2";
} else {
    echo "$str1 大于 $str2";
}

Output: apple 小于 banana

Example 2

$str1 = "apple";
$str2 = "apple";
$result = strcmp($str1, $str2);
if ($result == 0) {
    echo "两个字符串相等";
} elseif ($result < 0) {
    echo "$str1 小于 $str2";
} else {
    echo "$str1 大于 $str2";
}

Output: 两个字符串相等

Example 3

$str1 = "banana";
$str2 = "apple";
$result = strcmp($str1, $str2);
if ($result == 0) {
    echo "两个字符串相等";
} elseif ($result < 0) {
    echo "$str1 小于 $str2";
} else {
    echo "$str1 大于 $str2";
}

Output: banana 大于 apple

The strcmp() function therefore determines the relationship between two strings by comparing their ASCII values, returning 0 for equality, a negative value when the first string is smaller, and a positive value when it is larger.

Java学习资料领取

C语言学习资料领取

前端学习资料领取

C++学习资料领取

php学习资料领取

Backend DevelopmentPHPCode Examplestring comparisonstrcmp
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.