isset(), empty(), is_null() - What's the difference?

I came across an articleon phpro.org about the difference between isset, empty and isnull methods that I found it informative so I’m going to summarize and re-post it here.

There are often times where you need to check for empty or null values or if a variable is set. It’s pointed out that in many circumstances the wrong function is used to make these assertions. The code may end up working; however, in some cases using the wrong function returns a value that programmer didn’t expect and leads to errors.

Actions speak much louder than words so I’ll cut to the example. The example script tests the following functions and operators:

  • isset()
  • empty()
  • is_null()
  • ==
  • ===

against the following values:

  • no value set
  • null
  • zero
  • false
  • numeric value
  • empty string

and builds out a comparison table (see below) of the results. The notice above the table is because the isset() function is trying to check a variable that has not been initialized(Not Set).

I’ll be honest, I never knew passing a zero into the empty() function returns a true!

Anyways, the chart below ends up becoming a useful reference guide as well. The code used to produce the table is at the bottom of this post.

The Code

<?php
    /*** turn on error reporting ***/
    error_reporting( E_ALL );

    /*** an array of test values ***/
    $values = array( $var, null, 0, false, 100, '');
    echo '<tr>';
    echo '<td>isset()</td>';
    foreach( $values as $val )
    {
        echo '<td>';
        var_dump( isset( $val ) );
        echo '</td>';
    }
    echo '</tr>';

        echo '<tr>';
    echo '<td>empty()</td>';
        foreach( $values as $val )
        {
                echo '<td>';
                var_dump( empty( $val ) );
                echo '</td>';
        }
    echo '</tr>';

        echo '<tr>';
        echo '<td>is_null()</td>';
        foreach( $values as $val )
        {
                echo '<td>';
                var_dump( is_null( $val ) );
                echo '</td>';
        }
        echo '</tr>';

        echo '<tr>';
    echo '<td>==</td>';
        foreach( $values as $val )
        {
                echo '<td>';
                var_dump( $val == false  );
                echo '</td>';
        }
    echo '</tr>';

        echo '<tr>';
    echo '<td>===</td>';
        foreach( $values as $val )
        {
                echo '<td>';
                var_dump( $val === false );
                echo '</td>';
        }
        echo '</tr>';
?>
</tbody>
</table>

Questions or comments about this? Email us at contact@setfive.com.