PHP strncmp() Function

Definition
In PHP, strncmp() compares the first N characters of two strings, and it is case-sensitive.
It is handy for prefix checks, such as testing whether a URL starts with "https://".
Syntax
Call strncmp() with the values you need. Start with this line.
$result = strncmp("apple pie", "apple tart", 5);
| Call | What it does |
|---|
strncmp("apple pie", "apple tart", 5) | Returns 0 because the first 5 characters match. |
strncmp("Apple", "apple", 5) | Returns a negative number because case is different. |
strncmp($url, "https://", 8) === 0 | True when the URL starts with https://. |
A negative length throws a ValueError in PHP 8. On PHP 8.0 and later, str_starts_with() is usually a cleaner choice for simple prefix checks.
Library declarations
strncmp(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 Start of Two Strings
Only the first five characters are checked.
<?php
$result = strncmp("apple pie", "apple tart", 5);
echo $result, PHP_EOL;
How It Works
- Pass two strings and a length of 5.
- PHP looks at the first five characters of each.
- Both start with "apple", so they match.
- The function returns 0.
Example 2 — Case-Sensitive Result
A different letter case counts as a difference.
<?php
$result = strncmp("Apple", "apple", 5);
echo $result === 0 ? "Match" : "No match", PHP_EOL;
How It Works
- Compare "Apple" and "apple" for 5 characters.
- The first letters differ in case.
- strncmp treats them as different.
- Use strncasecmp() if you want to ignore case.
Frequently Asked Questions
It compares the first N characters of two strings in a case-sensitive way and returns 0 if they are equal.
Yes. 'Apple' and 'apple' are different. Use strncasecmp() for case-insensitive comparison.
On PHP 8.0 and later, use str_starts_with($string, $prefix). On older versions, use strncmp($string, $prefix, strlen($prefix)) === 0.
PHP compares up to the end of the shorter string. A longer string is considered greater if the shorter one matches so far.
A negative number, 0, or a positive number. From PHP 8.2 the values are -1, 0, or 1.
Next: strpbrk()
strpbrk() searches a string for any one of several characters and returns the rest of the .
strpbrk() 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