I've already asked a similar question here in StackOverlow at:
However, taking a look at some of the strange things that exist in PHP, I have seen that the following expression returns true
.
var_dump('2 porcos' + '3 cavalos' == '5 animais'); // bool(true)
I even agree that in PHP, the expression "2 porcos" + "3 cavalos"
will return int(5)
, due to the conversion of the initial numeric strings to type int
.
But why does the comparison return true
, since the content is completely different?
Of course, ==
compares only the values, but we see clearly that the values are not equal.
I agree that the example below is correct:
var_dump('2 porcos' + '3 cavalos' == 5); // bool(true)
However, this expression would not have to return false
?
var_dump(5 == '5 animais'); // bool(true)
And even more questionable:
var_dump(5 == '00005 animais'); // bool(true);
Of course, when we do the conversion, "00005 animais"
returns 5
, but why is this valid in comparison? This is bad.
I also noticed that in php 5 == '5 cãezinhos'
returns true
.
And this can be a problem for those who do not know these "curiosities" of language.
See some examples below
5 == '5 cavalos'; // true
'5' == '5 cavalos'; false
'5' == 5; // true
'5 ' == 5; // true
' 5' == 5; // true
Questions:
- Does PHP always convert the values to then compare them?
- When can I trust the comparison operation (
==
) and when can I only trust the identical operator (===
)?