Reputation: 502
Can somebody explain to me why this codes returns "TRUE". I know that i should use the "===" rather "==" but I run to this code and wondering why it returns to true. Thanks in advance.
<?php
$s = "final";
$i = 0;
if($s == $i){
echo "TRUE";
}else{
echo "FALSE";
}
Upvotes: 0
Views: 122
Reputation: 16351
Take a look at the PHP comparison tables.
You can see in the "Loose comparisons with ==" table that comparing the number 0 with a string containing text ("php" in the example) evaluates to TRUE
.
Upvotes: 1
Reputation: 1400
From PHP comparison operators:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
And from PHP string conversion to numbers:
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
So when you compare integer and a string, PHP tries to convert string to integer first and as "final" doesn't contain any valid numeric data, it is converted to 0.
You can try:
var_dump( intval('12final') ); //int(12)
var_dump( floatval('1.2final') ); //float(1.2)
This is because of both 12final
and 1.2final
start with valid numeric data (12
and 1.2
respecrively), their converted value is not 0.
Upvotes: 1
Reputation: 129
As mentionned above, it is an issue with php's loose comparison. The accepted answer on php string comparasion to 0 integer returns true? Explains it well enough IMHO. in short "==" attempts to cast your string into an int, and since it fails, the resulting int has a value of 0
Upvotes: 1
Reputation: 1179
When you are trying to compare string and number, interpretator converts your string to int, so you got 0 == 0 at final. Thats why string == 0
is true.
Upvotes: 5
Reputation: 1519
This is just a property of the loose comparisons implemented in PHP. I wouldn't search for any more logic behind this than that this is a given.
Upvotes: 1