Remove NULL values from PHP arrays with 1 line

Reading time: About 0 minutes

I had an array with something like the following: Array ( [0] => [1] => test [2] => fun ). But I don’t want [0], the empty value in the array.

After searching the web for a good solution, I saw that people were using anywhere from 4 to 10+ lines of code to remove null values from arrays. This is obviously overkill so I decided to tackle the problem myself.

Remove NULL values only

1
$new_array_without_nulls = array_filter($array_with_nulls, 'strlen');

Remove any FALSE values

This includes NULL values, EMPTY arrays, etc. Thanks to Paul Scott for pointing out this method.

1
$new_array_without_nulls = array_filter($array_with_nulls);

7 comments skip to comment form

  1. Drew Douglass said— 12 minutes later

    Nice stuff Brian, I’m assuming array_map() would work similarly to array_filter() in this situation?

    I’m a big fan of these quick one liners, keep them coming buddy!

    #1
  2. Paul Scott said— 11 hours later

    As far as I remember, you don’t need the 2nd arg to array_filter to remove NULL values. just $array_without_nulls = array_filter($array_with_nulls); will do

    #2
  3. Brian Cray said— 11 hours later

    Paul: Updated. Thanks so much for your valuable and obviously superior knowledge :)

    #3
  4. Cometbus said— 2 days later

    I do not see any way to do this correctly without iterating each item and explicitly unsetting each null. You could pass a unset null function to the array filter, but it is still more than one line. Maybe a regex could get it to one line.

    Currently, this method is dangerous, as it will remove a lot more than just nulls…

    $test_array = array('a', 'b', 'c', '1', '2', '3', null, FALSE, 0, TRUE, 1, '');

    $new_array_without_nulls = array_filter($test_array);

    print_r($test_array);
    print_r($new_array_without_nulls);

    Array
    (
    [0] => a
    [1] => b
    [2] => c
    [3] => 1
    [4] => 2
    [5] => 3
    [6] =>
    [7] =>
    [8] => 0
    [9] => 1
    [10] => 1
    [11] =>
    )
    Array
    (
    [0] => a
    [1] => b
    [2] => c
    [3] => 1
    [4] => 2
    [5] => 3
    [9] => 1
    [10] => 1
    )

    As you can see, both false and empty strings were removed. A lot of this has to do with php being a bit strange in what it calls a boolean/null/empty etc.

    Not saying this is not a good thing, just that it could cause you unappreciable behavior. Arrays are often used as a place to store boolean data, and this would clobber that data on the false side of it.

    #4
  5. Brian Cray said— 2 days later

    Cometbus:

    You’re right about that. I added my original code for this tutorial, which removes ONLY NULL values.

    #5
  6. David said— 3 months later

    is_scalar will work for Cometbus’ sample array.

    #6
  7. NXie said— on April 25, 2009 later

    Nice job. Exactly what I was looking for.

    #7
  8. Respond to this post—

Return to navigation
437