PHP strncasecmp() Function
Topic: PHP String ReferencePrev|Next
Description
The strncasecmp() function compares two strings up to a specified length.
This function is case-insensitive. For case-sensitive searches, use the strncmp() function.
The following table summarizes the technical details of this function.
| Return Value: | Returns a negative value (< 0) if string1 is less than string2; a positive value (> 0) if string1 is greater than string2, and 0 if both strings are equal. |
|---|---|
| Version: | PHP 4.0.2+ |
Syntax
The basic syntax of the strncasecmp() function is given with:
The following example shows the strncasecmp() function in action.
Example
Run this code »<?php
// Sample strings
$str1 = "Hello World!";
$str2 = "HELLO WORLD!";
// Performing string comparison
if(strncasecmp($str1, $str2, 5) === 0) {
echo "The two sub-strings are equal in a case-insensitive comparison.";
}
?>
Note: The strncasecmp() function is similar to strcasecmp(), except that in strncasecmp() you can specify the number of characters from each string to be used in the comparison.
Parameters
The strncasecmp() function accepts the following parameters.
| Parameter | Description |
|---|---|
| string1 | Required. Specifies the first string to compare. |
| string2 | Required. Specifies the second string to compare. |
| length | Required. Specifies the maximum number of characters to use in the comparison. |
More Examples
Here're some more examples showing how strncasecmp() function actually works:
The following example demonstrates the comparison of the first five characters of the two strings.
Example
Run this code »<?php
// Sample strings
$str1 = "Airport";
$str2 = "Airplane";
// Comparing the first five characters
echo strncasecmp($str1, $str2, 5);
?>
The following example shows the comparison of the first seven characters of the two strings.
Example
Run this code »<?php
// Sample strings
$str1 = "Hello John!";
$str2 = "hello johnny!";
// Comparing the first seven characters
echo strncasecmp($str1, $str2, 7);
?>

