Remove empty values from an array.

I developed this little one liner to remove empty values from an array in php.

$tags = array( ‘testtag’, ‘testtag2’, ‘ ‘ );

$tagsCleaned = array_filter( array_map( ‘trim’, $tags ),
create_function( ‘$a’, ‘return $a!=””;’ ) );

Breaking that down inside out.

array_map( ‘trim’, $tags )

Array map the trim function to all of the values within the array, removing removing pre/post spaces. In this case it removes the space in the third item.

array_filter( array_map( ‘trim’, $tags ),
create_function( ‘$a’, ‘return $a!=””;’ ) )

Array filter allows us to remove the elements that do not match the function. In this case, I’ve created a function to test if the value is an empty string. If it is, the function returns true if it is not blank and false if it is. The false return removes the value from the array.

The result will be an array of two items.

$tags = array( ‘testtag’, ‘testtag2’, ‘ ‘ );
$tagsCleaned = array_filter( array_map( ‘trim’, $tags ), create_function( ‘$a’, ‘return $a!=””;’ ) );
print_r($tagsCleaned);

 

Array
(
[0] => testtag
[1] => testtag2
)