Home  >  Article  >  Backend Development  >  The difference between 0, " ", null and false in php

The difference between 0, " ", null and false in php

WBOY
WBOYOriginal
2016-08-08 09:26:21830browse

Many people in PHP still don’t understand the difference between 0, "", null and false in PHP. These differences sometimes affect the correctness and security of data judgment, causing a lot of trouble for the test run of the program.
Let’s look at an example first:

$str1 = null;

$str2 = false;

echo $str1==$str2 ? 'Equal' : 'Not equal';

$str3 = " ";

$str4 = 0;

echo $str3==$str4 ? 'Equal' : 'Not equal';

$str5 = 0;

$str6 = '0';

echo $str5= ==$str6 ? 'Equal' : 'Not equal';

$str7=0;

$str=false;

echo $str7==$str8 ? 'Equal' : 'Not equal';

? >
Run result:

//Equal, equal, not equal, equal.
The reason is that variables in PHP are stored in C language structures. Empty strings, NULL, and false are all stored with a value of 0. This structure has a member variable like zend_uchartype;. It is used to save the type of variables, and the type of empty string is string, the type of NULL is NULL, and false is boolean.

You can use echo gettype(''); and echogettype(NULL); to print this! The === operator not only compares values, but also compares types, so the third one is false!
So it can be said that === is equal to the following function:

functioneq($v1,$v2) {
if(
$v1==$v2&&gettype($v1) ==gettype($v2)) {
return
1;
} else {
return
0;
}
}

So empty string (''), false, NULL and 0 are equal in value but different in type!

Note:

NULL is a special type.
NULL in two cases
1. $var = NULL;
2. $var;3."", 0, "0", NULL , FALSE, array(), var $var; and objects without any attributes will be considered empty. If var is empty, TRUE is returned.

The above introduces the differences between 0, " ", null and false in PHP, including relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn