Here you go, a complete breakdown of what works and when:
<?
echo "<pre>";
$nullVariable = null;
echo 'is_null($nullVariable) = ' . (is_null($nullVariable) ? 'TRUE' : 'FALSE') . "\n";
echo 'empty($nullVariable) = ' . (empty($nullVariable) ? 'TRUE' : 'FALSE') . "\n";
echo 'isset($nullVariable) = ' . (isset($nullVariable) ? 'TRUE' : 'FALSE') . "\n";
echo '(bool)$nullVariable = ' . ($nullVariable ? 'TRUE' : 'FALSE') . "\n\n";
$emptyVariable = '';
echo 'is_null($emptyVariable) = ' . (is_null($emptyVariable) ? 'TRUE' : 'FALSE') . "\n";
echo 'empty($emptyVariable) = ' . (empty($emptyVariable) ? 'TRUE' : 'FALSE') . "\n";
echo 'isset($emptyVariable) = ' . (isset($emptyVariable) ? 'TRUE' : 'FALSE') . "\n";
echo '(bool)$emptyVariable = ' . ($emptyVariable ? 'TRUE' : 'FALSE') . "\n\n";
//note that the only one that won't throw an error is isset()
echo 'is_null($nonexistantVariable) = ' . (@is_null($nonexistantVariable) ? 'TRUE' : 'FALSE') . "\n";
echo 'empty($nonexistantVariable) = ' . (@empty($nonexistantVariable) ? 'TRUE' : 'FALSE') . "\n";
echo 'isset($nonexistantVariable) = ' . (isset($nonexistantVariable) ? 'TRUE' : 'FALSE') . "\n";
echo '(bool)$nonexistantVariable = ' . (@$nonexistantVariable ? 'TRUE' : 'FALSE') . "\n\n";
?>
THE OUTPUT:
is_null($nullVariable) = TRUE
empty($nullVariable) = TRUE
isset($nullVariable) = FALSE
(bool)$nullVariable = FALSE
is_null($emptyVariable) = FALSE
empty($emptyVariable) = TRUE
isset($emptyVariable) = TRUE
(bool)$emptyVariable = FALSE
is_null($nonexistantVariable) = TRUE
empty($nonexistantVariable) = TRUE
isset($nonexistantVariable) = FALSE
(bool)$nonexistantVariable = FALSE
When I show (bool)$variable
above, that is how you could use it in a conditional. For example, to check if a variable is null or empty, you could do:
if (!$variable)
echo "variable is either null or empty!";
But it's best to use a function since it's a little more readable. But it's your choice.
Also, check the PHP type comparison table. It's basically what I just did above, except much more.