Home  >  Article  >  Backend Development  >  How to determine whether two strings are equal in php? Share in multiple ways

How to determine whether two strings are equal in php? Share in multiple ways

PHPz
PHPzOriginal
2023-03-20 15:34:495262browse

In PHP, there are many ways to determine whether two strings are equal. Below we will introduce the use and differences of these methods in detail.

Method 1: Use the "==" operator

The most common method is to use the "==" operator to determine whether two strings are equal. For example:

$str1 = "Hello";
$str2 = "hello";
if($str1 == $str2) {
    echo "相等";
} else {
    echo "不相等";
}

The running result will be "not equal". This is because the "==" operator is not case-sensitive when determining whether two strings are equal.

If you need to be case sensitive, you can use the "===" operator. For example:

$str1 = "Hello";
$str2 = "hello";
if($str1 === $str2) {
    echo "相等";
} else {
    echo "不相等";
}

The running result will be "not equal".

Method 2: Use the strcmp() function

The strcmp() function can be used to compare the size relationship between two strings. The return value is 0 indicating two characters. Strings are equal. For example:

$str1 = "Hello";
$str2 = "hello";
if(strcmp($str1, $str2) == 0) {
    echo "相等";
} else {
    echo "不相等";
}

The running result will be "not equal".

Method 3: Use strcasecmp() function

The strcasecmp() function is similar to the strcmp() function, except that it is not case-sensitive. For example:

$str1 = "Hello";
$str2 = "hello";
if(strcasecmp($str1, $str2) == 0) {
    echo "相等";
} else {
    echo "不相等";
}

The running result will be "equal".

Method 4: Use the substr_compare() function

The substr_compare() function can compare whether part of two strings are equal. For example:

$str1 = "Hello World";
$str2 = "World";
if(substr_compare($str1, $str2, 6) == 0) {
    echo "相等";
} else {
    echo "不相等";
}

The running result will be "equal" because the 7th character of $str1 starts with $str2 and is equal.

The above are several methods for determining string equality in PHP. It should be noted that when using the "==" operator to determine whether two strings are equal, it is not case-sensitive. If case sensitivity is required, the "===" operator or strcmp() function should be used. If you only need to compare part of two strings for equality, you can use the substr_compare() function.

The above is the detailed content of How to determine whether two strings are equal in php? Share in multiple ways. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn