PHP Remove Empty Array Elements

I’ve had multiple occasions when I encounter an array with empty elements that need to be skipped or removed before further parsing can continue.
A simple for loop will work, but that seems a little excessive since PHP has a ton of array functions.

Lets start off with a sample array:

<?php

$myarray = array('foo','',0,'bar',' ',"\n",'                ');

?>

This is what we want to reduce the array to:

<?php

array('foo',0','bar');

?>

I’m sure I could have used the array_reduce function, but the perl in me decided to use preg_grep.

<?php

$myarray = preg_grep('/\s+|^$/',$myarray,PREG_GREP_INVERT);

?>

This is short, sweet, and to the point. It removes our newlines and removes empty string elements from the array.
I’d be happy to see anyone else post alternatives as comments, that provide the same functionality of course.

~ by ityndall on December 3, 2010.

Leave a Reply