Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP strncmp() function

Reference for PHP strncmp(): compare the first n bytes of two strings, case-sensitive, with return values, strncasecmp(), and prefix checks.

strncmp() compares at most the first $length bytes of two strings. It is case-sensitive and binary-safe. The return value works like strcmp(): negative, zero or positive.

It is a classic way to test whether a string begins with a prefix. In modern code, str_starts_with() is clearer, but strncmp() is still useful when you also need ordering.

PHP
<?php
var_dump(strncmp("Hello world", "Help", 3));  // int(0)

Try it

PHP Comparing prefixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Length edge cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
strncmp(string $string1, string $string2, int $length): int
strncasecmp(string $string1, string $string2, int $length): int
Name Description
$string1 The first string.
$string2 The second string.
$length The maximum number of bytes to compare. Must not be negative.

Return value: a negative number, 0 or a positive number (only the sign is reliable).

Errors: throws a ValueError if $length is negative.

Usage notes

  • Zero-length comparison is equal. strncmp($a, $b, 0) returns 0.
  • Case-insensitive variant: strncasecmp() takes the same arguments and folds ASCII case.
  • Not a boolean. 0 means equal, so test with === 0.
  • Bytes, not characters. With multibyte text, a length that ends inside a UTF-8 character compares incomplete characters.
  • Prefer str_starts_with() (PHP 8.0+) when you only need a yes/no answer about a prefix.
  • Ordering of unequal strings still works: the result tells you which one sorts first within those bytes.