How to Remove Empty Array Elements in PHP?

Learn how to remove empty elements from an array in PHP.

Problem:

You have an array which has some values as well as few empty elements (see the following array). You want to remove those empty values from the array.

<?php
     $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday",  "Saturday", "Sunday");
?>

Solution:

This is one of the most common problems in everyday programming.
We can solve it in two different methods.

Method 1: Using array_filter() function

<pre>
<?php
    $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday",  "Saturday", "Sunday");
    $week_day = array_filter($week_days);
    print_r($week_day);
?>
</pre>

Download Code179 downloads

How it Works:

The array_filter() function removes all the elements from an array which are equal to boolean FALSE. Empty string is equal to boolean false. So, array_filter() function removes all those empty-string elements and returns elements with values.

Integer 0 or string “0” is also equal to boolean zero. Well, if you like to keep those values in the array, what you’ll do? See the second method-

Method 2: Using array_diff() function

<pre>
<?php
    $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday",  "Saturday", "Sunday");
    print_r(array_diff($week_days, array("")));
?>
</pre>
Download Code173 downloads

Output:

How it works:

The array_diff() function returns an array which has all the elements of the first array except those are present in the second array. The second array only contains an empty string. So, array_diff() function returns an without any empty string element.

Sort array-keys serially

In the above two examples, you’ve seen that the keys of the removed elements are missing in the resultant array. If you want to serialize the keys, use array_values() function. Let’s rewrite the last example -

<pre>
<?php
    $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday",  "Saturday", "Sunday");
    print_r(array_values(array_diff($week_days,array( "" ))));
?>
</pre>

Download Code172 downloads



Pin It

↑ Back to Top