String Comparison in PHP
When you develop a web application, it is common to need comparing two strings. String comparison is a fundamental operation in PHP or other programming languages.
Whether you’re checking user input, validating form fields, sorting values, or building complex logic, properly comparing two strings is essential.
For example, when you log in to a website like Gmail, Facebook, or Amazon, the system compares the email you entered with the one stored in the database. Even if you type your email as User@Example.com, the system usually matches it to user@example.com. Here, the string comparison is done without considering case differences.
Functions to Compare Strings in PHP
PHP provides several built-in functions that make it easy to perform string comparison in PHP. They are as:
- strcmp() function
- strcasecmp() function
- strncmp() function
- strncasecmp() function
- strnatcmp() function
- strnatcasecmp() function
- substr_compare() function
Let’s understand each function one by one for string comparison in PHP.
String Comparison using strcmp() Function in PHP
The strcmp() function in PHP compares two strings. It performs a case-sensitive comparison, which means that it considers uppercase and lowercase letters to be different. This function follows the ASCII values of characters, where uppercase letters have lower values than lowercase letters. The general syntax to define strcmp() function in PHP is as:
int strcmp(string $string1, string $string2)
In the above syntax, the strcmp() function accepts two strings as arguments. $string1 is the first string to compare, while $string2 is the second string to compare.
Return Values:
The strcmp() function returns an integer value depending on the match. It returns:
- Zero if the two strings are equal.
- Less than zero if the first string is less than the second string (i.e. appears alphabetically).
- Greater than zero if the first string is greater than the second string (i.e. it appears later in alphabetical order).
Example 1: Equal Strings
<?php
$str1 = "Hello";
$str2 = "Hello";
$result = strcmp($str1, $str2);
echo $result;
?>
Output: 0
In this example, both strings are exactly the same, so the result is 0.
Example 2: Case-Sensitive Comparison
<?php
$str1 = "Hello";
$str2 = "hello";
$result = strcmp($str1, $str2);
echo $result;
?>
Output: -1
In this example, the ASCII value of H is 72, while the ASCII value of h is 104. Since str1 < str2, so the result is negative.
Example 3: Different Strings
<?php
$str1 = "orange";
$str2 = "banana";
$result = strcmp($str1, $str2);
echo $result;
?>
Output: 1
In this example, the ASCII value of o is 111 while the ASCII value of b is 98. Since str1 > str2, the result is positive.
String Comparison using strcasecmp() Function in PHP
The strcasecmp() function in PHP is a built-in function that compares two strings in a case-insensitive manner. This function is similar to strcmp() function, but it ignores the case (uppercase or lowercase) of the characters while comparing. The general syntax to define strcasecmp() function is as follows:
strcasecmp(string $string1, string $string2): int
Return Values:
The strcmp() function returns an integer value depending on the match. It returns:
- Zero if the two strings are equal (ignoring case).
- Less than zero if the first string is less than the second string (i.e. appears alphabetically).
- Greater than zero if the first string is greater than the second string (i.e. it appears later in alphabetical order).
Example 4: Case-Insensitive Equality
<?php
$str1 = "Hello";
$str2 = "hello";
$result = strcasecmp($str1, $str2);
echo $result;
?>
Output: 0
In this example, both strings $str1 and $str2 are the same when the case is ignored. So, the function returns 0.
Example 5:
<?php
$str1 = "apple";
$str2 = "Banana";
$result = strcasecmp($str1, $str2);
echo $result;
?>
Output: -1
You can use the strcasecmp() function in PHP programming when you want to compare two strings without worrying about uppercase or lowercase. For example, you can use this function for comparing usernames, checking email domain, validating form fields like country names, city names, etc.
Example 6: Compare usernames without case sensitivity
<?php
$userInput = "JohnDoe";
$storedUsername = "johndoe";
if (strcasecmp($userInput, $storedUsername) == 0) {
echo "Login successful!";
} else {
echo "Invalid username.";
}
?>
Output: Login successful!
In this PHP code, a user types “JohnDoe”, but the database stores “johndoe”. Therefore, the string comparison still passes.
Compare Strings using strncmp() Function in PHP
PHP provides a built-in strncmp() function that is used to compare the first n characters of two strings. This function performs a case-sensitive comparison of the specified number of characters from each string. The general syntax to define strncmp() function is as:
strncmp(string $string1, string $string2, int $length): int
The strncmp() function takes three arguments, such as:
- $string1 is the first string to compare.
- $string2 is the second string to compare.
- $length is the number of characters to compare from the beginning of each string.
Return Values:
The strncmp() function returns an integer value depending on the match. It returns:
- Zero if the first n characters of both strings are equal.
- Less than zero if the first string is less than the second string (i.e. appears alphabetically).
- Greater than zero if the first string is greater than the second string (i.e. it appears later in alphabetical order).
Example 7:
<?php
$str1 = "HelloWorld";
$str2 = "HelloPHP";
$result = strncmp($str1, $str2, 5);
echo $result;
?>
Output: 0
In this example, we have defined the length 5 in the strncmp() function. Therefore, this function compares only the first 5 characters (Hello). Since they are identical, the result is 0.
Example 8: Case-Sensitive
<?php
$str1 = "Apple";
$str2 = "apple";
$result = strncmp($str1, $str2, 5);
echo $result;
?>
Output: -1
In this PHP code, the ASCII value of A is less than the ASCII value of a. Therefore, the output is -1.
Example 9: Filtering Items by Starting Letters
<?php
$names = ["Alice", "Albert", "Alex", "Bob", "Amanda"];
foreach ($names as $name) {
if (strncmp($name, "Al", 2) === 0) {
echo $name . "\n";
}
}
?>
Output: Alice Albert Alex
In this example, we have a contact list and want to find names that start with “Al”. For this, we have used strncmp() function to perform this operation.
PHP strncasecmp() Function for String Comparison
The strncasecmp() function in PHP is a built-in function that is used to compare the first n characters of two strings. It performs a case-insensitive comparison of the specified number of character from each string. It simply ignores character casing while string comparison. In other words, it treats uppercase and lowercase letters as equal while string comparison. The general syntax is as:
strncasecmp(string $string1, string $string2, int $length): int
Example 10:
<?php
$str1 = "Scientech";
$str2 = "scientech";
$result = strncasecmp($str1, $str2, 5);
echo $result;
?>
Output: 0
In this example, the first 5 characters of both strings are “Scientech” and “scientech”. Since the comparison is case-insensitive, the result is 0.
PHP strnatcasecmp() Function for Comparing Strings
The strnatcasecmp() function is a built-in function provided by PHP which is used to compare two strings using a “natural order” algorithm. This function ignores case sensitivity, while string comparison. Natural order means that string comparison is done based on the actual numeric values inside the strings, not character by character. The general syntax is as:
strnatcasecmp(string $string1, string $string2): int
This function accepts two arguments as strings such as:
- $string1 is the first string to compare.
- $string2 is the second string to compare.
Return Values:
The strnatcasecmp() function returns an integer value depending on the match. It returns:
- Zero if the first n characters of both strings are equal in natural order (ignoring case).
- Less than zero if the first string is less than the second string.
- Greater than zero if the first string is greater than the second string.
Example 11:
<?php
$file1 = "File10.txt";
$file2 = "file2.txt";
$result = strnatcasecmp($file1, $file2);
echo $result;
?>
Output: 1
In this example code, the strnatcasecmp() function compares two strings. Since the number 10 inside the first string is greater than the number 2 inside the second string, and also ignores the case of “File” and “file”, the result is 1.
Substring Comparison using substr_compare() Function
PHP provides a built-in substr_compare() function, which is used to compare a part (substring) of one string with another string. This function performs a case-insensitive optionally. The substr_compare() function is a powerful when you want to compare just a portion of a string from a specific position. The general syntax to define substr_compare() function is as follows:
substr_compare(
string $main_string,
string $compare_string,
int $start,
?int $length = null,
bool $case_insensitive = false
): int
The substr_compare() function accepts five arguments such as:
- $main_string represents, the original string to compare from.
- $compare_string specifies the string to compare with.
- $start specifies the position in $main_string where comparison starts (0-based index).
- $length specifies the number of characters to compare. If omitted, compare to the end. However, it is optional.
- $case_insensitive is also optional. If it is true, it will ignore case. However, it is set at false for case-sensitive by default.
Return Values:
The substr_compare() function returns an integer value depending on a match. This function returns:
- 0 if the compared strings are equal.
- < 0 if the substring from $main_string is less than $compare_string.
- > 0 if the substring from $main_string is greater than $compare_string.
Example 12:
<?php
echo substr_compare("HelloWorld", "World", 5);
?>
Output: 0
In this PHP code, string comparison starts at index 5 in the main string “HelloWorld”, which is “World”. It matches the compare string “World” exactly, so the result is 0.
Example 13: With Case-Insensitive Comparison
<?php
echo substr_compare("SCIENTECH", "tech", 5, null, true);
?>
Output: 0
In this example, the substr_compare() function compares “TECH” from index 5 with “tech” while ignoring case.
String comparison functions provided by PHP perform an ASCII based comparison of each character. If the ASCII codes of two strings are equal, then the functions returns zero. If the ASCII value of the first string is less than the second, it returns a negative number. If it is greater, a positive number is returned. I hope that all these things you understood and practiced all examples based on the discussed functions.