What is the difference between null and empty?

2019-01-10 18:15发布

I am new to the concept of empty and null. Whilst I have endeavoured to understand the difference between them, I am more confused. I came across an article at http://www.tutorialarena.com/blog/php-isset-vs-empty.php however I still don't see when you would use isset and empty when validating forms. Seeing that I don't grasp the difference, I don't want to be using the incorrect functions as well as not be able to use the functions in other areas. Can someone give examples that will help me understand? I am very new to coding so would appreciate if someone could give me real world examples and at the same time keep it simply enough for noob to follow.

标签: php null isset
9条回答
ら.Afraid
2楼-- · 2019-01-10 18:38

isset() returns true if both these conditions are met:

  1. The variable has been defined and has not yet been unset.
  2. The variable has a non-null value in it.

A variable is automatically defined when it gets set to something (including null). This has a direct implication in arrays.

$a=array();
$a['randomKey']=true;
$a['nullKey']=null;
var_dump(isset($a['randomKey'])); // true
var_dump(isset($a['nullKey'])); // true, the key has been set, set to null!
var_dump(isset($a['unsetKey'])); // false !
unset($a['randomKey']);
var_dump(isset($a['randomKey'])); // false ! it's been unset!

From above, you can check if various $_POST fields have been set. For example, a page that has been posted to, stands to reason, has the submit button name in the $_POST field.

empty() on the other hand, tests if the variable holds a non zero value. This means that values that (int) cast to 0, return false too. You can use this to see if a specific $_POST field has data in it.

查看更多
Deceive 欺骗
3楼-- · 2019-01-10 18:45

The table below is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool(false). enter image description here

refer this link for more https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-10 18:48

This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).

Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.

In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null. The second example is akin to empty.

查看更多
登录 后发表回答