Current Location: Home> Latest Articles> Comprehensive Guide to PHP String Comparison Methods with Code Examples

Comprehensive Guide to PHP String Comparison Methods with Code Examples

M66 2025-08-02

Introduction to PHP String Comparison Methods

In PHP development, string comparison is a common and essential operation. PHP offers multiple ways to determine the relationship between strings. This article will explain these comparison methods and their use cases one by one.

Equality (==) to Compare String Values

The double equal operator checks whether the values of two strings are the same, ignoring their types.

$str1 = "Hello world";
$str2 = "Hello world";

if ($str1 == $str2) {
    // Returns true
}

Strict Equality (===) to Compare Both Value and Type

Strict equality compares not only the string content but also the variable types to ensure they are identical.

$str1 = "Hello world";
$str2 = new String("Hello world");

if ($str1 === $str2) {
    // Returns false because types differ
}

Inequality (!=) to Check if String Values are Different

The not equal operator checks whether the content of two strings is different.

$str1 = "Hello world";
$str2 = "Hello moon";

if ($str1 != $str2) {
    // Returns true
}

Strict Inequality (!==) to Check Value or Type Differences

Strict inequality determines if either the value or the type of two strings differs.

$str1 = "Hello world";
$str2 = new String("Hello world");

if ($str1 !== $str2) {
    // Returns true because types differ
}

Greater Than (>) and Less Than (<) for Lexicographical Comparison

When comparing strings, PHP uses lexicographical order (based on ASCII values) to determine which string is greater or smaller.

$str1 = "Hello";
$str2 = "World";

if ($str1 > $str2) {
    // Returns false
}

if ($str1 < $str2) {
    // Returns true
}

Greater Than or Equal To (>=) and Less Than or Equal To (<=) for Lexicographical or Equality Check

These operators check if one string is greater than or equal to, or less than or equal to another string.

$str1 = "Hello";
$str2 = "Hello";

if ($str1 >= $str2) {
    // Returns true
}

if ($str1 <= $str2) {
    // Returns true
}

Conclusion

With these multiple string comparison methods, PHP developers can choose flexibly according to their needs to ensure accurate and efficient program logic. Mastering these basics is crucial for handling string data effectively.