Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 856
Josh Avatar asked Aug 30 '11 16:08

Josh


2 Answers

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.

like image 153
Marc B Avatar answered Sep 27 '22 17:09

Marc B


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

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

like image 20
hometoast Avatar answered Sep 27 '22 18:09

hometoast