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";
    }
3

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.