The strncasecmp Function

The strncasecmp function performs a case-insensitive comparison of the first specified n characters of two strings. It returns 0 if the substrings are equal, a negative number if the first string is less than the second, and a positive number if the first string is greater.

Syntax

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

Example

Case-insensitive comparison of the first 4 characters:

php<?php
  $res = strncasecmp("Hello", "HELP me", 4);
  echo $res;
?>

Code execution result:

php0

Example

Comparison with a case difference:

php<?php
  $res = strncasecmp("apple", "APRICOT", 3);
  echo $res;
?>

Code execution result (negative number, because 'p' < 'R'):

php-8

Example

Case-insensitive prefix check:

php<?php
  $header = "Content-Type: application/json";
  if (strncasecmp($header, "content-type:", 12) === 0) {
    echo '+++';
  }
?>

Code execution result:

php'+++'

See Also

  • the strncmp function,
    which compares the first n characters case-sensitively
  • the strcasecmp function,
    which compares strings in full without case sensitivity