Reputation: 327
<?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
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
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