String comparison is a common task in PHP when checking equality, sorting values, validating input, or performing case-sensitive/insensitive checks. PHP provides several operators and functions to compare strings effectively.
1. Comparing Strings Using Operators
a) Equal (==)
Checks if two strings have the same value, case-sensitive.
$str1 = "Hello";
$str2 = "Hello";
if ($str1 == $str2) {
echo "Strings are equal";
}
b) Identical (===)
Checks value and type.
$str1 = "123";
$str2 = 123;
if ($str1 === $str2) {
echo "Same";
} else {
echo "Not same"; // Output
}
c) Not Equal (!= or <>)
if ("apple" != "banana") {
echo "Different strings";
}
2. Case-Insensitive Comparison
Use strcasecmp().
if (strcasecmp("Hello", "hello") == 0) {
echo "Same (case-insensitive)";
}
3. Natural Order Comparison (strnatcmp)
Useful when comparing strings with numbers.
echo strnatcmp("file2", "file10"); // file2 < file10
4. Comparing Portions of Strings
Use strncmp() to compare first n characters.
echo strncmp("HelloWorld", "HelloPHP", 5); // 0 means equal
5. Using strcmp()
Standard binary-safe string comparison.
$result = strcmp("abc", "abd");
if ($result < 0) echo "abc < abd";
if ($result > 0) echo "abc > abd";
if ($result == 0) echo "Equal";
6. Comparing Strings with Spaces & Trimming
$str1 = " Hello ";
$str2 = "Hello";
if (trim($str1) === trim($str2)) {
echo "Equal after trimming";
}
7. Safe Comparison for User Input
Always sanitize before comparing.
$user = strtolower(trim($_POST['username']));
$actual = "admin";
if ($user === $actual) {
echo "Access granted";
}
Conclusion
String comparison in PHP can be simple or advanced based on your needs—using operators for basic checks and functions like strcmp() and strcasecmp() for more control.
Citations
🔗 View other articles about PHP:
http://savanka.com/category/learn/php/
🔗 External PHP Documentation:
https://www.php.net/manual/en/