The strncmp Function

The strncmp function performs a binary-safe comparison of the first n characters of two strings, case-sensitively. Like strcmp, it returns 0 if they are equal, a negative number if the first string is less, and a positive number if it is greater.

Syntax

phpstrncmp(string $str1, string $str2, int $length): int

Example

Comparing the first 3 characters of identical strings:

php<?php
  $res = strncmp("Hello", "Help me", 3);
  echo $res;
?>

Code execution result:

php0

Example

Comparing the first 4 characters of different strings:

php<?php
  $res = strncmp("apple", "apricot", 4);
  echo $res;
?>

Code execution result (negative number, because 'l' < 'r'):

php-8

Example

Checking a string prefix:

php<?php
  $url = "https://example.com";
  if (strncmp($url, "https://", 8) === 0) {
    echo "Secure connection";
  }
?>

Code execution result:

php"Secure connection"

See Also

  • the strcmp function,
    which compares strings in their entirety
  • the strncasecmp function,
    which compares the first n characters case-insensitively