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
Syntax
strcmp(string $string1, string $string2): int
Parameters
| Parameter | Description |
|---|---|
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
<?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)
<?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,=== 0or> 0, not=== -1. - For equality,
$a === $bis clearer. Usehash_equals()to compare secrets such as tokens.
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
string.localeCompare()· JavaScript
Related
strcasecmp()· Compare two strings without caring about ASCII upper and lower case. Returns 0 if they match.strncmp()· Compare only the first n bytes of two strings, case-sensitively. Handy for checking a prefix in older code.strnatcmp()· Compare strings in natural order, so "img2" comes before "img10" the way people expect. Case-sensitive.usort()· Sort an array's values with your own comparison function, in place. Keys are discarded. Use <=> for easy comparisons.- PHP Strings · tutorial