5

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?

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
JohnA
  • 1,875
  • 8
  • 28
  • 34

5 Answers5

3

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?

Community
  • 1
  • 1
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
3

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.

Ken Wayne VanderLinde
  • 18,915
  • 3
  • 47
  • 72
1

In your first line, you define $my_var as string.

Inside the comparison you compare that variable with a constant integer.

If you want exact comparison (I don't know why you need to compare a string with an integer without any cast), you should use the ===:

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

That will never echo the message.

The PHP manual defines in Comparison Operators section, the operator == as:

TRUE if $a is equal to $b after type juggling.

So, the important thing here is type juggling.

As a matter of fact, in PHP Manual: types comparisons, the second table tell you exactly that integer 0 equals string "".

Nicolás Ozimica
  • 9,481
  • 5
  • 38
  • 51
1

This is due to the type coercion that comes from the equality operator you are using.

The PHP manual has the Type Comparison tables to shed a light on this.

Its generally considered a good practice to utilize the identical operator === instead, as to avoid such corner(?) cases.

Nathan
  • 4,017
  • 2
  • 25
  • 20
0

here is the reference in the php manual about boolean values

http://www.php.net/manual/en/language.types.boolean.php

and here is the reference for the NULL value

http://www.php.net/manual/en/language.types.null.php

$my_var = '';

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

evaluates to true because "" is the same as NULL which evaluates to false or 0