Skip to content


Remove empty array elements in PHP

Here is a quick tip on how to remove elements with empty values. All you have to use is the array_filter($myarray) function. Here is an example.


$myarray = array();
$myarray[] = 1;
$myarray[] = '';
$myarray[] = 'a';

print_r($myarray);

Array
(
[0] => 1
[1] =>
[2] => a
)

When you use array_filter() this is what you get:

$myarray = array_filter($myarray);
print_r($myarray);

Array
(
[0] => 1
[1] => a
)

Of course you can use array_filter with a callback function to intelligently remove elements, but if you just want to remove empty values, this is the best way.

Posted in PHP.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.