-2
I’ve asked a similar question here at Stackoverlow at: Why in PHP the expression "2 + '6 apples'" is 8?
However, taking a look at some strange things curiosities that exist in PHP, I saw 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)
, on account of the conversion of the initial numeric strings to the type int
.
But why does comparison return true
, since the content is completely different?
It is certain that ==
compares only the values, but we clearly see 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 terms of 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:
- PHP at all times converts the values and then compares them?
- When can I trust the comparison operation (
==
) and when I can rely only on the operator of identical (===
)?
I do not know the principle used for comparison in PHP, maybe it is due to the fact of the initial purpose of the language. But, there goes the confusion even more in the explanation -> http://php.net/manual/en/types.comparisons.php What I do is always use === to be sure.
– user31138
'5 ' == 5 // true
– Guilherme Lautert
The answers to the previous question have already been sufficiently enlightening, if you want to take into account the type use
===
– Guilherme Lautert
var_dump('5 ' == 5);
of false?– rray
@Wallacemaxters operators are not the same thing, but the answer is the same. The question is not the operators but how PHP works with the data.
– KaduAmaral