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

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

Example

Comparison of identical strings:

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

Code execution result:

php0

Example

Comparison of different strings (case-sensitive):

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

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

php-32

Example

Usage in conditional statements:

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

Code execution result:

php"Password is correct"

See Also

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