PHP strncmp() Function

Quick summary: The PHP strncmp() function compares the first N characters of two strings.

PHP strncmp() Syntax

strncmp(string $string1, string $string2, int $length): int
PHP

PHP strncmp() Basic examples

var_dump(strncmp("abcdef", "abcxyz", 3));
PHP
Output:
int(0)

The first 3 characters are equal.

var_dump(strncmp("abcdef", "abzxyz", 3));
PHP
Output:
int(-1)

Comparison stops after the specified length.

PHP strncmp() Real-world usage

$token = "Bearer abc123";
if (strncmp($token, "Bearer ", 7) === 0) {
    echo "Valid token";
}
PHP
Output:
Valid token

Checks for a string prefix.

PHP strncmp() Edge cases

var_dump(strncmp("abc", "abcdef", 10));
PHP
Output:
int(0)

Comparison stops when the shorter string ends.

PHP strncmp() Common mistakes

Assuming strncmp is case-insensitive

strncmp is case-sensitive.

Incorrect
strncmp("ABC", "abc", 3);
Correct
strncasecmp("ABC", "abc", 3);

Use strncasecmp() for case-insensitive comparison.

PHP strncmp() Frequently Asked Questions

What does strncmp() do in PHP?

strncmp() compares the first N characters of two strings.

What does strncmp() return?

strncmp() returns 0 if the compared parts are equal, a negative value if the first is less, and a positive value if the first is greater.

Is strncmp() case-sensitive?

Yes, strncmp() is case-sensitive. Use strncasecmp() for case-insensitive comparison.

What is the third parameter in strncmp()?

The third parameter specifies how many characters to compare.

What happens if N is larger than string length?

strncmp() compares up to the available length without causing an error.

How to check prefix equality using strncmp()?

Use strncmp($a, $b, $n) === 0 to check if the first N characters match.

What is the difference between strcmp() and strncmp()?

strcmp() compares full strings, while strncmp() compares only the first N characters.

Is strncmp() binary-safe?

Yes, strncmp() is binary-safe and works with raw byte data.

Does strncmp() modify strings?

No, strncmp() does not modify the input strings.

Can strncmp() be used for validation?

Yes, it is often used to validate prefixes such as checking URL schemes or tokens.

What is a real-world use case of strncmp()?

strncmp() is commonly used to check prefixes, such as verifying if a string starts with a specific value.

What is the difference between strncmp() and str_starts_with()?

strncmp() compares a fixed number of characters, while str_starts_with() directly checks if a string starts with a given substring.

PHP strncmp() Related PHP Functions