How to Compare Strings in PHP
Comparing strings is a fundamental task in PHP development, whether you’re validating user input, sorting data, or building search functionality. PHP offers several built‑in functions and operators that handle string comparison in different contexts—case‑sensitive, case‑insensitive, locale‑aware, and natural order. This guide walks you through each method, shows practical code examples, and highlights best practices for performance and security.
Table of Contents
- Strict Equality (===) and Inequality (!==)
- strcmp() – Binary Safe Comparison
- strcasecmp() – Case‑Insensitive Comparison
- Locale‑Aware Comparison with mbstring
- Natural Order Sorting (natsort, strnatcmp)
- Best Practices & Common Pitfalls
1. Strict Equality (===) and Inequality (!==)
The simplest way to compare two strings is using the strict equality operator (===) or the strict inequality operator (!==). These operators check both value and type, making them safe for security‑critical checks such as password verification.
Example
$a = "Hello";
$b = "Hello";
if ($a === $b) {
echo "Exact match!";
} else {
echo "No match.";
}
Key points:
- Case‑sensitive: “Hello” !== “hello”.
- Type‑safe: The string
"123"is not equal to the integer123when using===.
2. strcmp() – Binary Safe Comparison
strcmp() compares two strings byte by byte (binary safe) and returns an integer:
0if the strings are equal.- A negative number if the first string is less than the second.
- A positive number if the first string is greater than the second.
Example
$first = "apple";
$second = "banana";
$result = strcmp($first, $second);
if ($result < 0) {
echo "$first comes before $second";
} elseif ($result > 0) {
echo "$first comes after $second";
} else {
echo "Both strings are identical";
}
Because strcmp() is binary safe, it works correctly with strings that contain null bytes (\0).
3. strcasecmp() – Case‑Insensitive Comparison
When you need to ignore case, use strcasecmp(). It follows the same return‑value convention as strcmp() but treats uppercase and lowercase letters as equal.
Example
$a = "PHP";
$b = "php";
if (strcasecmp($a, $b) === 0) {
echo "Strings match regardless of case.";
}
4. Locale‑Aware Comparison with mbstring
For multilingual applications, binary comparison may produce unexpected results with accented characters. The mbstring extension provides mb_strcmp() (via mb_strcasecmp() in newer PHP versions) and collator_compare() (from the intl extension) to respect locale rules.
Using mb_strcasecmp()
// Ensure mbstring is loaded
if (!function_exists('mb_strcasecmp')) {
die('mbstring extension is required.');
}
$a = "résumé";
$b = "RESUME";
if (mb_strcasecmp($a, $b, 'UTF-8') === 0) {
echo "Locale‑aware case‑insensitive match.";
}
Using the Intl\Collator class
$collator = new Collator('fr_FR'); // French locale
$a = "côte";
$b = "cote";
if ($collator->compare($a, $b) === 0) {
echo "Strings are equal in French collation.";
}
The Collator approach handles complex rules such as diacritics, ligatures, and language‑specific sorting order.
5. Natural Order Sorting (natsort, strnatcmp)
When strings contain numbers (e.g., “file1”, “file10”, “file2”), a lexical comparison puts “file10” before “file2”. PHP’s natural order functions sort the numbers as humans expect.
Example with strnatcmp()
$files = ["file2.txt", "file10.txt", "file1.txt"];
usort($files, "strnatcmp");
print_r($files);
// Output: ["file1.txt", "file2.txt", "file10.txt"]
Example with natsort()
6. Best Practices & Common Pitfalls
- Choose the right function for the job. Use
===for exact matches,strcmp()for binary safe lexical ordering, andmb_strcasecmp()orCollatorfor internationalized text. - Beware of type juggling. The loose equality operator (
==) can lead to security bugs (e.g.,"0e12345" == "0"evaluates totrue). Prefer strict checks. - Normalize Unicode strings. Even with locale‑aware functions, differing Unicode normal forms (NFC vs NFD) can cause mismatches. Use
Normalizer::normalize()from theintlextension before comparison. - Cache heavy objects. Creating a
Collatorinstance is relatively expensive. Reuse the same instance for multiple comparisons within a request. - Performance tip. For large data sets,
===andstrcmp()are faster than locale‑aware functions. Profile your code if performance is critical.
Conclusion
PHP offers a rich set of tools for string comparison, each tailored to specific scenarios—from fast binary checks with === to sophisticated, locale‑aware collation using Intl\Collator. Understanding the nuances of each method helps you write code that is both correct and performant, especially when dealing with internationalized content.