strncmp

(PHP 4, PHP 5)

strncmp --  Binary safe string comparison of the first n characters

Description

int strncmp ( string str1, string str2, int len )

This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(), strncasecmp(), strcasecmp(), substr(), stristr(), strcmp(), and strstr().


add a note add a note User Contributed Notes
Anonymous
17-Apr-2002 07:46
strncmp("sample","sam",4) returns 1 because the final requirement is if one string terminates before len, then the other must also terminate at that position. 

You can imagine that all your strings have one more final, invisible "termination" character.  If that termination character happens to be within in len, then it must match, too.

For instance, write that termination character with, say, the sequence "\0". Then you can equivalently consider that function call as strncmp("sample\0","sam\0",4).

So, the "p" in "sample" does not match the termination character in "sam".