PHP: strncmp() function


The strncmp() function compare two strings of the first n characters.

Note : The comparison is case sensitive.


(PHP 4 and above)


strncmp(string1, string2, no_of_characters)


Name Description Required /
string1 The first string. Required String
string2 The second string. Required String
no_of_characters Specified the number of characters from each string to be used in the comparison. Required Integer

Return value:

< 0 if string1 < string2.
> 0 if string1 > string2.
0 if string1 = string2.

Value Type: Integer.


echo strncmp('Hello John...', 'Hello Anirban....', 6);

Output :


View the example in the browser

See also

PHP Function Reference

Previous: strncasecmp
Next: strrchr

PHP: Tips of the Day

In PHP, there are two versions of logical AND and OR operators.

Operator True if
$a and $b Both $a and $b are true
$a && $b Both $a and $b are true
$a or $b Either $a or $b is true
$a || $b Either $a or $b is true

Note that the && and || opererators have higher precedence than and and or. See table below:

Evaluation Result of $e Evaluated as
$e = false || true True $e = (false || true)
$e = false or true False ($e = false) or true

Because of this it's safer to use && and || instead of and and or.