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.

php Courses
php Courses
php Courses
Understanding PHP strcmp() Function: Syntax, Parameters, Return Values, and Examples
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

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

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

$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 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.

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.

BackendPHPTutorialstring-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.