PHP 8 reference · String Functions

PHP strcmp() Function

Compare two strings byte by byte, case-sensitively. Returns 0 when equal, less than 0 or more than 0 otherwise.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

strcmp(string $string1, string $string2): int

Parameters

ParameterDescription
string1 The first string.
string2 The second string.

Return value

0 if equal; a negative number if string1 sorts first; a positive number otherwise.

Examples

Compare stringsTry it yourself
<?php
var_dump(strcmp("apple", "apple"));
var_dump(strcmp("apple", "banana") < 0);
var_dump(strcmp("a", "A") > 0); // lowercase sorts after uppercase

Output

int(0)
bool(true)
bool(true)
Sort with strcmp()Try it yourself
<?php
$names = ["bob", "Alice", "carol"];
usort($names, "strcmp");
print_r($names);

Output

Array
(
    [0] => Alice
    [1] => bob
    [2] => carol
)

Common mistakes

  • Only the sign of the result matters. Test < 0, === 0 or > 0, not === -1.
  • For equality, $a === $b is clearer. Use hash_equals() to compare secrets such as tokens.

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?