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);
437
7 comments skip to comment form
Drew Douglass said— 12 minutes later
Paul Scott said— 11 hours later
Brian Cray said— 11 hours later
Cometbus said— 2 days later
Brian Cray said— 2 days later
David said— 3 months later
NXie said— on April 25, 2009 later
Respond to this post—