PHP empty var == 0?

In php 5

  $my_var = "";

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

  }

Why does he value the truth? Are there any links to php.net about this?

+5
source share
5 answers

PHP is a weakly typed language . Empty lines and a boolean false will be evaluated equal to 0 when testing with the equal operator ==. On the other hand, you can force it to check the type using an identical statement ===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 this: How do comparison operators compare PHP equalities (== double equals) and identities (=== triple equals)?

+3
source

==. , PHP , , .

, . . , "" , 0. , 0 == 0, , , .

, === ( ) .

+3

$my_var .

.

( , - ), ===:

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

.

PHP " " , == :

, $a $b .

, type juggling.

, PHP Manual: , , 0 string "".

+1

, .

The PHP manual contains type comparison tables to shed light on this.

It is generally considered good practice to use an identical operator ===instead to avoid such angular (?) Cases.

+1
source

here is the link in php manual on booleans

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

and here is the link 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"
}

true because "" matches a NULL value that evaluates to false or 0

0
source

All Articles