0
<?php

// your code goes here
if (0 == "asdf")
    echo "same";
else
    echo "not same";

Hello, Why this code prints "same", not "not same"? I'm little bit confused about this weird result. Is this a bug?

Execution Result: see http://ideone.com/wfWRlq

4

3 Answers 3

6

No, this is not a bug the string just get's converted to a int. It converts it from left to right until a non numeric value. So since there is a non numeric value right at the start it gets converted to 0.

For more information about String to int see the manual: http://php.net/manual/de/language.types.string.php#language.types.string.conversion

And a quote from there:

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 as an example to show that:

echo "5xyz" + 5;  // 5 + 5 -> 10
    //^
echo "xyz5" + 5;  // 0 + 5 -> 5
       //^
echo "x5z"  + 5;  // 0 + 5 -> 5
     //^
Sign up to request clarification or add additional context in comments.

1 Comment

"asdf" == 0 returns true too :)
1

You should use ===. Because that do convert type of value.

Comments

1

That's one of non-intuitive behaviors of comparisons in PHP. There's == operator for loose comparison, what checks only values of given variables and === operator for strict comparison, what checks also types of variables. PHP manual has dedicated page with comparisons tables.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.