String comparison using '==' or '===' vs. 'strcmp()'
In PHP, you can use either the ==
or ===
operator to compare two strings. The ==
operator will compare the values of the strings, while the ===
operator will compare both the value and the type of the strings.
For example:
<?php
$string1 = "abc";
$string2 = "abc";
$string3 = "123";
if ($string1 == $string2) {
echo '$string1 == $string2 is true' . PHP_EOL;
// this will be true, since the values of $string1 and $string2 are the same
}
if ($string1 === $string2) {
echo '$string1 === $string2 is true' . PHP_EOL;
// this will also be true, since the values and types of $string1 and $string2 are the same
}
if ($string1 === $string3) {
echo '$string1 === $string3 is true' . PHP_EOL;
// this will be false, since the type of $string1 is string and the type of $string3 is integer
} else {
echo '$string1 === $string3 is false' . PHP_EOL;
}
Watch a video course
Learn object oriented PHP
You can also use the strcmp()
function to compare two strings. This function will return 0 if the strings are equal, a positive number if the first string is greater than the second, and a negative number if the first string is less than the second.
For example:
<?php
$string1 = "abc";
$string2 = "abc";
$string3 = "def";
if (strcmp($string1, $string2) == 0) {
echo 'strcmp($string1, $string2) == 0 is true' . PHP_EOL;
// this will be true, since the strings are equal
}
if (strcmp($string1, $string3) < 0) {
echo 'strcmp($string1, $string3) < 0 is true' . PHP_EOL;
// this will be true, since "abc" comes before "def" alphabetically
}
It's generally recommended to use the ===
operator or strcmp()
for string comparison, since the ==
operator can sometimes give unexpected results when comparing strings that contain numbers.