Current Location: Home> Latest Articles> Detailed Explanation and Use Cases of the !== Operator in PHP

Detailed Explanation and Use Cases of the !== Operator in PHP

gitbox 2025-06-25

1. === Operator

In PHP, ===

The code above compares two different values. Since the types of variables $a and $b are different—one is an integer and the other is a string—the === operator returns false, and the output is "Not equal".

2. !== Operator

!== is the inequality operator in PHP, which functions oppositely to ===. It is used to compare whether two values have different types or values. If the types are different or the values are different (even if the types are the same), the !== operator returns true; otherwise, it returns false.

$a = 5;
$b = '5';
if ($a !== $b) {
    echo 'Not equal';
} else {
    echo 'Equal';
}

The code above compares the variables $a and $b. Since the values of $a and $b are different, even though their types are the same, the !== operator returns true, and the output is "Not equal".

3. Use Cases for !==

The !== operator is very useful in various situations. Below are a few common use cases:

(1)Type Checking

When you need to check whether a variable's type is different from the expected type, you can use the !== operator. For example:

$value = 5;
if (gettype($value) !== 'integer') {
    echo 'The type of $value is not an integer';
} else {
    echo 'The type of $value is an integer';
}

The code above uses the gettype() function to get the type of the variable $value and compares it to the string 'integer'. If they are not equal, the output will be "The type of $value is not an integer".

(2)Value Checking

When you need to check whether a variable's value is different from the expected value, you can use the !== operator. For example:

$name = 'Alice';
if ($name !== 'Bob') {
    echo 'Not Bob';
} else {
    echo 'Is Bob';
}

The code above compares the variable $name with the string 'Bob'. Since their values are not equal, the output is "Not Bob".

(3)Checking if a Variable Exists

In some cases, you may need to check if a variable exists. In PHP, you can use the !== operator to check if a variable is null. For example:

$variable = null;
if ($variable !== null) {
    echo 'Variable exists';
} else {
    echo 'Variable does not exist';
}

The code above checks whether the variable $variable is null. Since $variable is null, the output will be "Variable does not exist".

4. Conclusion

The !== operator in PHP is used to compare two values for inequality, either by type or value. It is the opposite of the === operator, which checks for strict equality. In actual development, you can use the !== operator to verify if the type or value of a variable meets your expectations.

Through this article, we have learned about the use of the !== operator and its applicable scenarios, with examples of its practical use. We hope this article helps you understand and use the !== operator in PHP more effectively.