PHP 8 reference · String Functions
PHP strncmp() Function
Compare only the first n bytes of two strings, case-sensitively. Handy for checking a prefix in older code.
PHP 8 Since 4.0
Syntax
strncmp(string $string1, string $string2, int $length): int
Parameters
| Parameter | Description |
|---|---|
string1 |
The first string. |
string2 |
The second string. |
length |
How many bytes to compare. |
Return value
0 if the first length bytes match; negative or positive otherwise.
Examples
<?php
var_dump(strncmp("ReadyCamel", "Ready", 5) === 0);
var_dump(strncmp("ReadyCamel", "ready", 5) === 0);
Output
bool(true) bool(false)
<?php
foreach (["ERR-12", "OK-3", "ERR-7"] as $code) {
if (strncmp($code, "ERR", 3) === 0) {
echo $code, "\n";
}
}
Output
ERR-12 ERR-7
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
Related
strcmp()· Compare two strings byte by byte, case-sensitively. Returns 0 when equal, less than 0 or more than 0 otherwise.str_starts_with()· Check whether a string begins with a given substring. Case-sensitive and returns true or false; added in PHP 8.0.- PHP Strings · tutorial