The difference between $ a = 0 and $ a = '0' in PHP

In my code there was an if statement similar to the one below, and I always needed to find 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 really don't know what is going on here.

+5
source share
3 answers

One line, one integer. PHP will translate between them as needed, unless you use the "strict" operators:

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

In your case, you are comparing the integer 0 with the string "something." PHP converts the string "something" into an integer. If there are no numbers at all, it will be converted to an integer 0, which makes your comparison true.

+4
source

Just a guess, but I assume that he is trying to pass a string to an integer.

intval('something') , 0.

+2

($a = 0;) . , PHP 0, , true.

In another case, however, you have two lines that are different from each other, so it is false .

0
source

All Articles