user2064468
user2064468

Reputation:

PHP - compare two diffrent type variable bug or issue

There is two different type of variables. but while comparing both variable using == operator it returns weired output. Is this bug or some other issue? I am surprised. Here is code,

$a=1000;
$b='1000square';
if($a==$b){
    echo "a equal b";
}else{
    echo "a not equal b";
}

It outputs : a equal b. But expected : a not equal b.

Can anyone explain?

Thanks!!!

Upvotes: 0

Views: 142

Answers (2)

keanpedersen
keanpedersen

Reputation: 50

There is a difference between == and === in PHP. See the documentation: https://www.php.net/manual/en/language.operators.comparison.php

What happens in the statement $a==$b is that PHP needs to decide how to compare $a and $b. Since at least one operand ($a) is a number, PHP uses numerical comparison instead of string comparison. Therefore $b is converted to a number. In PHP, the string '1000square' is converted to the number 1000. This is why your code shows that $a==$b is true.

However, $a===$b is false, since === compares the type as well. This might be the operator you are looking for.

Upvotes: 1

rid
rid

Reputation: 63442

$b gets typecast to a number so it can be compared to $a, therefore the resulting $b (the number 1000) will be equal to $a. You should use === instead of == if you want to find out if the two variables are identical, not just equal. === doesn't typecast, and only returns true if both variables are of the same type and equal.

Upvotes: 2

Related Questions