In this tutorial, you will learn how to compare two case insensitive strings in PHP.
How to Compare Case Insensitive String in PHP?
Here are two ways:
- Case-Insensitive String Comparison in PHP
- Using Case-Insensitive Comparison in Sorting
Case-Insensitive String Comparison in PHP
In PHP, you can perform case-insensitive string comparison using the strcasecmp()
or strnatcasecmp()
function.
Here’s an example of using strcasecmp()
to compare two strings case-insensitively:
$string1 = "Hello World"; $string2 = "hello world"; if (strcasecmp($string1, $string2) == 0) { echo "The two strings are equal."; } else { echo "The two strings are not equal."; }
Output:
The two strings are equal.
Now let’s take another example using strnatcasecmp()
:
$string1 = "Chapter 2: Introduction"; $string2 = "chapter 10: conclusion"; if (strnatcasecmp($string1, $string2) < 0) { echo "$string1 comes before $string2."; } else { echo "$string1 comes after $string2."; }
Output:
Chapter 2: Introduction comes before chapter 10: conclusion.
Using Case-Insensitive Comparison in Sorting
Case-insensitive string comparison is particularly useful when sorting arrays of strings, where case sensitivity can affect the ordering of the elements. In PHP, you can use the usort()
function with a custom comparison function that uses strcasecmp()
to perform case-insensitive sorting.
Here’s an example of sorting an array of strings case-insensitively:
$fruits = array("apple", "Orange", "banana", "kiwi", "pear"); usort($fruits, function($a, $b) { return strcasecmp($a, $b); }); print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => kiwi
[3] => Orange
[4] => pear
)
Conclusion
In summary, when comparing strings in PHP, it is important to consider case sensitivity. PHP provides two built-in functions strcasecmp()
and strnatcasecmp()
to perform case-insensitive string comparison.