PHP strncasecmp() Function

Definition
In PHP, strncasecmp() compares the first N characters of two strings, ignoring case.
It is useful for checking prefixes, like whether a command starts with "help" in any case.
Syntax
Call strncasecmp() with the values you need. Start with this line.
$result = strncasecmp($a, $b, 5);
| Call | What it does |
|---|
strncasecmp("Hello World", "hELLO there", 5) | Returns 0 because the first 5 letters match. |
strncasecmp("abc", "xyz", 0) | Returns 0 because no characters are compared. |
strncasecmp($cmd, "HELP", 4) === 0 | True when $cmd starts with "help" in any case. |
Since PHP 8.0, a negative length throws a ValueError. For case-sensitive prefix checks, use strncmp(), or str_starts_with() on PHP 8.0+.
Library declarations
strncasecmp(string $string1, string $string2, int $length): int
Parameters
| Parameter | Description |
|---|
| string1 | Required. The first string. |
| string2 | Required. The second string. |
| length | Required. The number of characters to compare. Must not be negative. |
Return Value
| Return Value | Description |
|---|
| int | Negative if string1 is less than string2, 0 if the compared parts are equal, positive if string1 is greater. |
PHP Examples
Example 1 — Compare the First Letters
Check whether two strings begin the same way, ignoring case.
<?php
$result = strncasecmp("Hello World", "hELLO there", 5);
echo $result, PHP_EOL;
How It Works
- Pass two strings and the number 5.
- Only the first five characters are compared.
- "Hello" and "hELLO" are equal when case is ignored.
- The function returns 0, which means a match.
Example 2 — Length of Zero
With a length of 0, nothing is compared at all.
<?php
echo strncasecmp("abc", "xyz", 0), PHP_EOL;
How It Works
- The two strings are completely different.
- A length of 0 tells PHP to compare nothing.
- No difference can be found.
- The result is 0. Be careful with the length value in real code.
Frequently Asked Questions
It compares the first N characters of two strings without caring about upper or lower case. It returns 0 when those characters are equal.
strncmp() is case-sensitive, while strncasecmp() ignores case. Both compare only the first N characters.
Since PHP 8.0, a negative length throws a ValueError. Always pass 0 or a positive number.
Use strncasecmp($string, $prefix, strlen($prefix)) === 0. PHP's str_starts_with() is case-sensitive, so it is not a replacement here.
It means the compared parts of both strings are equal. A negative or positive number means they differ.
Next: strncmp()
strncmp() compares the first N characters of two strings, and it is case-sensitive.
strncmp() tutorial →About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful