What is the difference between == and === in PHP ?


In PHP, == and === are comparison operators used to compare two values.

The main difference between == and === is that == compares the values of the two operands, while === compares both the values and the data types of the two operands.

Here are some examples to illustrate the difference:

$a = 5;
$b = "5";

// Using ==
if ($a == $b) {
    echo "Equal";
} else {
    echo "Not equal";
}
// Output: Equal

// Using ===
if ($a === $b) {
    echo "Equal";
} else {
    echo "Not equal";
}
// Output: Not equal

In the first example, $a and $b have the same value, so $a == $b returns true. In the second example, $a and $b have different data types ($a is an integer and $b is a string), so $a === $b returns false.

Another example:

$a = 5;
$b = "5";

// Using ==
if ($a == $b) {
    echo "Equal";
} else {
    echo "Not equal";
}
// Output: Equal

// Using ===
if ($a === $b) {
    echo "Equal";
} else {
    echo "Not equal";
}
// Output: Not equal

In this example, $a and $b have the same value, but $b is a string. When using ==, PHP will automatically convert the string to an integer and compare the values, so $a == $b returns true. However, when using ===, PHP compares both the value and the data type, so $a === $b returns false.

In summary, == compares the values of two operands, while === compares both the values and the data types of two operands. It is generally recommended to use === for more strict comparison, unless you specifically need to compare only the values and not the data types.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.