0

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";
    }
reignsly
  • 452
  • 2
  • 10
  • functions *return* (a value). code *prints* or *echo*es – Karoly Horvath Nov 28 '14 at 09:09
  • possible duplicate of [How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?](http://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp) – J. Steen Nov 28 '14 at 09:10
  • Thanks guys. I learned a lot today :) – reignsly Nov 28 '14 at 09:18

5 Answers5

5

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.

Efog
  • 1,126
  • 12
  • 33
1

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.

Allmighty
  • 1,440
  • 13
  • 19
1

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.

xlecoustillier
  • 15,451
  • 14
  • 56
  • 79
1

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

Community
  • 1
  • 1
user3816703
  • 99
  • 1
  • 3
1

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.

Zudwa
  • 1,250
  • 8
  • 12