Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP strcmp() function

Reference for PHP strcmp(): binary-safe, case-sensitive string comparison, its return values, use in usort(), and how it differs from == and <=>.

strcmp() compares two strings byte by byte and tells you which comes first. It is case-sensitive and binary-safe, so strings containing null bytes compare correctly.

It returns a negative number if the first string is smaller, a positive number if it is greater, and 0 if they are equal. The exact size of the number is not specified (it can be a byte difference or a length difference, and PHP 8.2 normalized some of these results to -1 and 1), so compare with < 0 and > 0 rather than with specific numbers.

PHP
<?php
var_dump(strcmp("apple", "banana") < 0);  // bool(true)

Try it

PHP Comparing strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Sorting with strcmp()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
strcmp(string $string1, string $string2): int
Name Description
$string1 The first string.
$string2 The second string.

Return value: a negative integer if $string1 sorts before $string2, a positive integer if after, 0 if equal. Only the sign is reliable.

Usage notes

  • Never test the result as a boolean. if (strcmp($a, $b)) is true when the strings are different. Write strcmp($a, $b) === 0 or just use ===.
  • Equality: === is the right operator for equal strings; strcmp() shines when you need ordering, for example in usort() callbacks. The spaceship operator <=> also compares strings, but it applies numeric comparison when both look numeric.
  • Case-sensitive. Use strcasecmp() to ignore ASCII case.
  • Not locale-aware. It compares raw bytes, so accented letters sort after z in UTF-8. Use Collator (intl) or strcoll() for language-aware order.
  • Natural numbers in text: "img10" sorts before "img2"; use strnatcmp() to fix that.
  • Partial comparison: strncmp() looks at only the first n bytes.
  • Timing attacks: for secrets such as tokens use hash_equals(), not strcmp().