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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
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

Compare a prefixTry it yourself
<?php
var_dump(strncmp("ReadyCamel", "Ready", 5) === 0);
var_dump(strncmp("ReadyCamel", "ready", 5) === 0);

Output

bool(true)
bool(false)
Filter codesTry it yourself
<?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

VersionChange
PHP 4.0Added

Was this page helpful?