The strncasecmp() function is used to compare a case-sensitive string of the first ‘n’ character. This function was introduced in PHP4. The comparison is case-insensitive—that is, “Alphabet” and “alphabet” are considered equal. This function is a case-insensitive version of strcmp(). If either string is shorter than length characters, the length of that string determines how many characters are compared.
Syntax:
strncasecmp(string $string1, string $string2, int $length): int
Parameters
Parameter | Description |
---|---|
string1 | The first string. |
string2 | The second string. |
length | The length of strings to be used in the comparison. |
Return Values
Returns 0 if string1 is greater than string2, and 0 if they are equal.
Examples
$var1 = 'Hello John'; $var2 = 'hello Doe'; if (strncasecmp($var1, $var2, 5) === 0) { echo 'First 5 characters of $var1 and $var2 are equals in a case-insensitive string comparison'; }
Final Thoughts
Use strncasecmp to compare the first parts of two strings. PHP compares the strings, character by character, until comparing the number of characters specified by length or reaching the end of one of the strings. PHP treats letters of different case as equal. If first and second are equal, PHP returns zero. If first comes before second, PHP returns a negative number. If second comes before first, PHP returns a positive number.