The strncmp() function behaves identically in PHP 8.4 and PHP 8.5. There are no version specific changes to this function in either release. Its most recent behavioral change occurred in PHP 8.2.0 regarding the exact integer value returned when strings differ in length.
Function
strncmp() performs a binary safe, case-sensitive comparison of the first $length characters of two strings.
Signature:
strncmp(string $string1, string $string2, int $length): int
Examples
Here is how you can use it in your PHP 8.4 or 8.5 projects:
1. Basic Usage (Checking a Prefix)
<?php
$var1 = Hello John ;
$var2 = Hello Doe ;// Compare only the first 5 characters
if (strncmp($var1, $var2, 5) === 0) {
echo First 5 characters are equal in a case-sensitive comparison ;
}
// Outputs: First 5 characters are equal in a case-sensitive comparison
?>
This is useful for checking if a string starts with a specific prefix.
2. Case Sensitivity Demonstration
<?php
$string1 = Hello ;
$string2 = hello ;$result = strncmp($string1, $string2, 5);
if ($result !== 0) {
echo The strings are NOT equal (case matters). ;
}
// Outputs: The strings are NOT equal (case matters).
?>
Unlike strncasecmp(), this function distinguishes between uppercase and lowercase letters.