Backend Development 4 min read

PHP strnatcmp() Function: Natural Order String Comparison

The article explains PHP’s strnatcmp() function, which compares two strings using natural order sorting, details its syntax, demonstrates usage with code examples showing how numeric parts are evaluated, and notes the case‑sensitive behavior and the alternative strnatcasecmp() for case‑insensitive comparisons.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP strnatcmp() Function: Natural Order String Comparison

strnatcmp() is a PHP string comparison function that compares two strings using natural order sorting rather than simple lexical order.

Natural order sorting compares numeric parts of strings based on their numeric value, so "file10.txt" is considered greater than "file2.txt".

Syntax of strnatcmp()

<code>int strnatcmp ( string $str1 , string $str2 )</code>

The function takes two string arguments and returns an integer: 0 if the strings are equal, a positive value if $str1 is greater than $str2 , and a negative value if $str1 is less than $str2 .

Usage Examples

Example 1

<code>$str1 = "file2.txt";
$str2 = "file10.txt";
$result = strnatcmp($str1, $str2);
if ($result > 0) {
    echo $str1 . " 大于 " . $str2;
} elseif ($result < 0) {
    echo $str1 . " 小于 " . $str2;
} else {
    echo $str1 . " 等于 " . $str2;
}
</code>

The output is: file2.txt 小于 file10.txt

Example 2

<code>$str1 = "file10.txt";
$str2 = "file2.txt";
$result = strnatcmp($str1, $str2);
if ($result > 0) {
    echo $str1 . " 大于 " . $str2;
} elseif ($result < 0) {
    echo $str1 . " 小于 " . $str2;
} else {
    echo $str1 . " 等于 " . $str2;
}
</code>

The output is: file10.txt 大于 file2.txt

These examples demonstrate that strnatcmp() follows natural order, comparing numeric portions as numbers rather than ASCII characters, which aligns with human intuition.

Note that strnatcmp() is case‑sensitive. To perform a case‑insensitive natural comparison, use strnatcasecmp() , which works similarly but ignores case differences.

Summary

strnatcmp() is a PHP function for comparing two strings using natural order sorting. It correctly handles strings containing numbers and produces results that match human expectations. When case‑insensitive comparison is needed, use strnatcasecmp() instead.

backendPHPstring comparisonnatural sortstrnatcmp
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.