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

user1035957
  • 327
  • 1
  • 3
  • 9
  • This has been asked before: http://stackoverflow.com/questions/8671942/php-string-comparasion-to-0-integer-returns-true – Sipty Feb 14 '15 at 16:22
  • You can cast the string to int, so that you compare same types – Cornea Ali Feb 14 '15 at 16:25
  • 1
    Because PHP is a terrible excuse for a language. Try Perl – Cole Tobin Feb 14 '15 at 17:15
  • possible duplicate of [Why does PHP consider 0 to be equal to a string?](http://stackoverflow.com/questions/6843030/why-does-php-consider-0-to-be-equal-to-a-string) – andrewsi Feb 15 '15 at 00:29

3 Answers3

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
     //^
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

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

vitalik_74
  • 4,573
  • 2
  • 19
  • 27
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.

pamil
  • 980
  • 2
  • 10
  • 20