Backend Development 3 min read

PHP strncasecmp() Function: Syntax, Parameters, Return Values, and Usage Example

strncasecmp() is a PHP string comparison function that compares the first n characters of two strings case‑insensitively, with detailed syntax, parameter explanations, return values, a practical code example, and usage notes on handling full‑string comparisons and typical applications.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP strncasecmp() Function: Syntax, Parameters, Return Values, and Usage Example

strncasecmp() is a PHP function that compares the first n characters of two strings without case sensitivity.

Syntax of strncasecmp()

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

Parameters

$str1 : the first string to compare.

$str2 : the second string to compare.

$len : the number of characters to compare.

Return Values

0 if the compared portions of the strings are equal.

A value less than 0 if $str1 is less than $str2 .

A value greater than 0 if $str1 is greater than $str2 .

Example Usage

<code>$str1 = "Hello World";
$str2 = "hello world";
$result = strncasecmp($str1, $str2, 5);
if ($result == 0) {
    echo "两个字符串的前5个字符相等";
} elseif ($result < 0) {
    echo "第一个字符串小于第二个字符串";
} else {
    echo "第一个字符串大于第二个字符串";
}
</code>

The above code outputs “两个字符串的前5个字符相等” because the comparison is case‑insensitive, so “Hello” and “hello” are considered equal.

Note that the function only compares the first n characters; to compare the entire string, set $len to the length of the strings.

This function is commonly used when case‑insensitive string comparison is required, such as checking equality or sorting strings alphabetically.

Summary

strncasecmp() compares the first n characters of two strings in PHP without case sensitivity, allowing developers to perform case‑insensitive comparisons by specifying the length to compare.

Backend DevelopmentPHPstring comparisoncase-insensitivestrncasecmp
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.