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
strncmp(string $str1, string $str2, int $length): int
Example
Comparing the first 3 characters of identical strings:
<?php
$res = strncmp("Hello", "Help me", 3);
echo $res;
?>
Code execution result:
0
Example
Comparing the first 4 characters of different strings:
<?php
$res = strncmp("apple", "apricot", 4);
echo $res;
?>
Code execution result (negative number, because 'l' < 'r'):
-8
Example
Checking a string prefix:
<?php
$url = "https://example.com";
if (strncmp($url, "https://", 8) === 0) {
echo "Secure connection";
}
?>
Code execution result:
"Secure connection"
See Also
-
the
strcmpfunction,
which compares strings in their entirety -
the
strncasecmpfunction,
which compares the first n characters case-insensitively