132 of 410 menu

The strcmp Function

The strcmp function performs a binary-safe, case-sensitive string comparison. It returns 0 if the strings are identical, a negative number if the first string is less than the second, and a positive number if the first string is greater than the second.

Syntax

strcmp(string $str1, string $str2): int

Example

Comparison of identical strings:

<?php $res = strcmp("Hello", "Hello"); echo $res; ?>

Code execution result:

0

Example

Comparison of different strings (case-sensitive):

<?php $res = strcmp("Apple", "apple"); echo $res; ?>

Code execution result (negative number because 'A' < 'a' in ASCII):

-32

Example

Usage in conditional statements:

<?php $password = "Secret123"; if (strcmp($password, "Secret123") === 0) { echo "Password is correct"; } else { echo "Password is incorrect"; } ?>

Code execution result:

"Password is correct"

See Also

  • the strcasecmp function,
    which compares strings case-insensitively
  • the strncmp function,
    which compares the first n characters of strings
byenru