user1035957
user1035957

Reputation: 327

Why zero (0) and string are the same in PHP?

<?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

Upvotes: 0

Views: 61

Answers (3)

pamil
pamil

Reputation: 980

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.

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

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
     //^

Upvotes: 6

vitalik_74
vitalik_74

Reputation: 4591

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

Upvotes: 1

Related Questions