String Functions

PHP strncmp() Function

Topic: PHP String ReferencePrev|Next


The strncmp() function compares two strings up to a specified length.

This function is case-sensitive. For case-insensitive searches, use the strncasecmp() 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+


The basic syntax of the strncmp() function is given with:

strncmp(string1, string2, length);

The following example shows the strncmp() function in action.

// Sample strings
$str1 = "Hello John!";
$str2 = "Hello Peter!";

// Comparing the first five characters
echo strncmp($str1, $str2, 5);

Note: The strncmp() function is similar to strcmp(), except that with strncmp() you can specify the number of characters from each string to be used in the comparison.


The strncmp() 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 strncmp() function actually works:

The following example shows the comparison of the first seven characters of the two strings.

// Sample strings
$str1 = "Hello John!";
$str2 = "Hello Peter!";

// Comparing the first seven characters
echo strncmp($str1, $str2, 7);

The following example demonstrates the case-sensitive behavior of this function.

// Sample strings
$str1 = "Hello World!";
$str2 = "HELLO World!";

// Performing string comparison
if(strncmp($str1, $str2, 5) !== 0) {
    echo "The portions of the two strings are not equal.";
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties