You can validate in many ways :
By using following php variable handling functions
is_null(mixed $var)
isset(mixed $var)
empty(mixed $var)
By using comparison operator ==
, ===
or !=
is_null(mixed $var)
You can use php variable handling function is_null(mixed $var)
which returns TRUE if var is null, otherwise FALSE.
<?php
$foo = NULL;
$bar = 'NULL';
var_dump(is_null($foo), is_null($bar));
?>
OUTPUT
bool(true) bool(false)
As you can see $bar = 'NULL'
and $bar = NULL
both are different thing. Actually, in one it is initializing with a string, not with NULL.
isset(mixed $var)
It returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Note
isset()
only works with variables as passing anything else will result in a parse error. For checking if constants are set use, the defined() function.
<?php
$foo = NULL;
$bar = 'NULL';
var_dump(isset($foo), isset($bar));
?>
OUTPUT
bool(false) bool(true)
empty(mixed $var)
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
<?php
$foo = NULL;
$bar = 'NULL';
var_dump(empty($foo), empty($bar));
?>
OUTPUT
bool(true) bool(false)
==
or ===
or !=
You can use comparison operator ==
, ===
or !=
to check whether a variable is null or not.
<?php
$foo = NULL;
$bar = 'NULL';
// Using == operator
echo "Using '==' operator\n";
if($foo == NULL)
echo "foo is NULL\n";
else
echo "foo is not NULL\n";
if($bar == NULL)
echo "bar is NULL\n";
else
echo "bar is not NULL\n";
// Using === operator
echo "\nUsing '===' operator\n";
if($foo === NULL)
echo "foo is NULL\n";
else
echo "foo is not NULL\n";
if($bar === NULL)
echo "bar is NULL\n";
else
echo "bar is not NULL\n";
?>
OUTPUT
Using '==' operator
foo is NULL
bar is not NULL
Using '===' operator
foo is NULL
bar is not NULL
The only difference between ==
and ===
is that ==
just checks to see if the left and right values are equal. But, the ===
operator (note the extra “=”) actually checks to see if the left and right values are equal and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.).