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.tu
There are some good answers here, which I won't repeat. In the case of validating forms, though, when a form is submitted, the value of each form input element is sent to the server in the $_POST
variable. You can check for the existence of a particular input by using isset()
.
isset($_POST['username'])
If this returns true, then this request to the server was the result of posting a form containing an input element named "username". Now that we know that we have a value for that form element, we can see if it has a valid value. empty()
will tell us whether the user actually entered any data in the field, or whether they left it empty.
empty($_POST['username'])
If that returns true then the form submitted to the server had a field named "username" but the user didn't enter anything into before submitting the form.
A variable is NULL
if it has no value, and points to nowhere in memory.
empty()
is more a literal meaning of empty, e.g. the string ""
is empty, but is not NULL
.
The following things are considered to be empty:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
- NULL
- FALSE
- array() (an empty array)
- var $var; (a variable declared, but without a value in a class)
Source.
$a
is NULL
.
$a = ''
is empty, but not NULL
.
If
$a=''
is empty but notNULL
, when do I use theempty()
function and when do I use theisset()
function.
isset() will return FALSE
is the variable is pointing to NULL
.
Use empty()
when you understand what is empty (look at the list above).
Also when you say it points nowhere in memory, what does that mean exactly?
It means that $str = ''
will be in memory as a string with length of 0.
If it were $str = NULL
, it would not occupy any memory.
The empty()
is a nice fast way to see if the variable holds any useful info... that is for strings empty()
returns true for a string of "" as well as a null string.
So you can write something like this:
if (! empty($name)) echo $name;
More info see here: PHP: empty()