strncasecmp() Function Use in PHP 8.4 and PHP 8.5

strncasecmp() behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes to this function in either release. The most recent behavioral change occurred in PHP 8.2.0 regarding its return value.

Function

strncasecmp() performs a binary-safe, case insensitive comparison of the first n characters of two strings.

Signature:

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

Return Value:

  • Returns < 0 if $string1 is less than $string2.
  • Returns > 0 if $string1 is greater than $string2.
  • Returns 0 if they are equal (within the compared length).

Examples

1. Basic Comparison (Checking Equality)

<?php
$var1 = Hello John ;
$var2 = hello Doe ;

// Compare only the first 5 characters, ignoring case
if (strncasecmp($var1, $var2, 5) === 0) {
   echo The first 5 characters are equal (case insensitive). ;
}
// Outputs: The first 5 characters are equal (case insensitive).
?>

This is the standard usage shown in the PHP manual. "Hello" and "hello" are considered equal for the first 5 characters.

2. Understanding the Return Value

<?php
// "Hello" vs "hELLo" (case difference only)
echo strncasecmp("Hello", "hELLo", 6); // Outputs: 0

// "Hello" vs "HelloWorld" (length difference)
echo strncasecmp("Hello", "HelloWorld", 6); // Outputs: a negative value (e.g., -1)
?>

The function only compares up to $length characters. If one string is shorter, the comparison uses that shorter length.

Notes

  • PHP 8.2+ Return Change: Since PHP 8.2.0, when the strings are not equal in length, the function is no longer guaranteed to return strlen($string1) - strlen($string2). It may now return -1 or 1 instead. You should only rely on the sign (negative, positive, or zero), not the exact integer value.
  • Binary Safe: You can safely use it with binary data.
  • Related Functions: For comparing the entire strings, use strcasecmp(). For case-sensitive comparison of the first n characters, use strncmp().


 

6 Views