Josh
Josh

Reputation: 63

Difference Between $a = 0 and $a = '0' in PHP

I had an if statement similar to the following in my code and it took me forever to figure out what the problem was.

$a = 0;
if($a == 'something')
 {
 //this was being output when I didn't want it to be
 }

Using

$a = '0'; 

fixed it, but I don't really know what's going on here.

Upvotes: 5

Views: 227

Answers (3)

aorcsik
aorcsik

Reputation: 15552

You were comparing a numeric value ($a = 0;) to a string. In this case the string is casted to number, and PHP cast strings to 0 if there is no number in the beginning, so is true.

In the other case however you campared two strings, which are different, so it is false.

Upvotes: 0

hometoast
hometoast

Reputation: 11782

Just a guess, but I assume it's trying to cast the string to an integer.

intval('something') I expect will return 0.

Upvotes: 2

Marc B
Marc B

Reputation: 360702

One's a string, one's an integer. PHP will translate between the two as needed, unless you're using the 'strict' operators:

(0 == '0') // true
(0 === '0') // false (types don't match).

In your case, you'r comparing an integer 0 to a string 'something'. PHP will convert the string 'something' to an integer. If there's no digits in there at all, it'll conver to an integer 0, which makes your comparison true.

Upvotes: 4

Related Questions