Master PHP’s strcmp(): Compare Strings Like a Pro

The article explains PHP’s strcmp() function, detailing its ASCII‑based string comparison mechanism, syntax, parameters, and return values, and provides three practical code examples that demonstrate how to determine whether one string is equal to, less than, or greater than another.

php Courses
php Courses
php Courses
Master PHP’s strcmp(): Compare Strings Like a Pro
strcmp()

is a PHP function that compares two strings based on their ASCII values.

PHP compares strings character by character using ASCII codes to determine their ordering.

strcmp() Function Syntax

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

The parameters $str1 and $str2 represent the two strings to compare. The function returns an integer indicating the relationship:

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 returns 0 for equal strings, a negative value when the first string is smaller, and a positive value when it is larger.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentPHPCode Examplesstring-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

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.