Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP empty var == 0?

In php 5

  $my_var = "";

  if ($my_var == 0) {
    echo "my_var equals 0";

  }

Why it evaluates true? Is there some reference in php.net about it?

like image 274
JohnA Avatar asked Mar 17 '12 04:03

JohnA


2 Answers

PHP is a weakly typed language. Empty strings and boolean false will evaluate to 0 when tested with the equal operator ==. On the other hand, you can force it to check the type by using the identical operator === as such:

$my_var = "";

if ($my_var === 0) {
   echo "my_var equals 0";
} else {
   echo "my_var does not equal 0";
}

This should give you a ton of information on the subject: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

like image 58
Jeremy Harris Avatar answered Sep 19 '22 10:09

Jeremy Harris


A string and an integer are not directly comparable with ==. So PHP performs type juggling to see if there is another sensible comparison available.

When a string is compared with an integer, the string first gets converted to an integer. You can find the details of the conversion here. Basically, since "" is not a valid number, the result of the conversion is 0. Thus, the comparison becomes 0 == 0 which is clearly true.

You'll probably want to use the identity comparison === for most (if not all) your comparisons.

like image 33
Ken Wayne VanderLinde Avatar answered Sep 19 '22 10:09

Ken Wayne VanderLinde