Removing empty array elements in PHP

To remove empty array elements in PHP, you can use several approaches. The most common methods include using array_filter() or manually iterating through the array with foreach and unset().

Using foreach and unset()

This method manually iterates through the array and removes empty elements ?

<?php
   $my_array = array("This", 91, '', null, 102, "is", false, "a", "sample", null);
   
   foreach($my_array as $key => $val) {
       if(empty($val)) {
           unset($my_array[$key]);
       }
   }
   
   echo "After removing empty values from the array:<br>";
   foreach($my_array as $key => $val) {
       echo $my_array[$key] . "<br>";
   }
?>
After removing empty values from the array:
This
91
102
is
a
sample

Using array_filter()

The array_filter() function provides a cleaner approach to remove empty elements ?

<?php
   $my_array = array("This", 91, '', null, 102, "is", false, "a", "sample", null);
   
   // Remove empty elements
   $filtered_array = array_filter($my_array);
   
   echo "Original array elements: " . count($my_array) . "<br>";
   echo "Filtered array elements: " . count($filtered_array) . "<br><br>";
   
   foreach($filtered_array as $val) {
       echo $val . "<br>";
   }
?>
Original array elements: 10
Filtered array elements: 6

This
91
102
is
a
sample

Comparison

Method Preserves Keys Code Length Performance
foreach + unset() Yes Longer Slower
array_filter() Yes Shorter Faster

Conclusion

Use array_filter() for cleaner, more efficient code when removing empty elements. The foreach approach gives you more control over the removal logic but requires more code.

Updated on: 2026-03-15T09:02:22+05:30

744 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements