PHP strcmp() Function
PHP strcmp() Syntax
strcmp(string $string1, string $string2): int
PHP strcmp() Basic examples
var_dump(strcmp("apple", "banana"));
int(-1)
Returns a negative number if the first string is less than the second.
var_dump(strcmp("apple", "apple"));
int(0)
Returns 0 when strings are equal.
var_dump(strcmp("banana", "apple"));
int(1)
Returns a positive number if the first string is greater.
PHP strcmp() Real-world usage
$role = "admin";
if (strcmp($role, "admin") === 0) {
echo "Access granted";
}
Access granted
Safely compares strings in conditionals.
PHP strcmp() Edge cases
var_dump(strcmp("Apple", "apple"));
int(-1)
Comparison is case-sensitive.
PHP strcmp() Common mistakes
Using strcmp as boolean
strcmp does not return true or false.
if (strcmp("a", "b")) { echo "Equal"; }
if (strcmp("a", "b") === 0) { echo "Equal"; }
Always compare the return value explicitly.
PHP strcmp() Frequently Asked Questions
What does strcmp() do in PHP?
strcmp() compares two strings and returns an integer indicating their lexical relationship.
What does strcmp() return?
strcmp() returns 0 if strings are equal, a negative value if the first is less, and a positive value if the first is greater.
Is strcmp() case-sensitive?
Yes, strcmp() is case-sensitive. Use strcasecmp() for case-insensitive comparison.
How to check if two strings are equal using strcmp()?
Check if strcmp($a, $b) === 0 to determine equality.
What is the difference between strcmp() and ===?
strcmp() compares strings lexically, while === checks strict equality including type.
Does strcmp() work with numbers?
strcmp() converts inputs to strings before comparison, so numbers are compared as strings.
Can strcmp() return boolean values?
No, strcmp() returns an integer, not a boolean.
Is strcmp() safe for binary data?
Yes, strcmp() is binary-safe and works with raw byte strings.
Does strcmp() consider string length?
Yes, if strings differ in length, strcmp() considers this in the comparison result.
What is a real-world use case of strcmp()?
strcmp() is commonly used for sorting, comparing user input, or implementing custom comparisons.
What is the difference between strcmp() and strcasecmp()?
strcmp() is case-sensitive, while strcasecmp() ignores case differences.
Does strcmp() modify the input strings?
No, strcmp() does not modify the input strings and only returns a comparison result.