In this tutorial, you shall learn how to remove empty strings in given array in PHP using array_filter() function, with the help of example programs.

PHP – Remove empty strings in array

To filter empty strings in given array in PHP, we can use array_filter() function.

Example

In this example, we take an array with strings in arr, and remove all the empty strings from the array using array_filter() function. Original array arr is unchanged, but array_filter() function returns an array where all the elements are non-empty strings.

PHP Program

<?php
  $arr = ["", "apple", "banana", "", "", "cherry"];

  $filtered = array_filter($arr, function ($item) {
    return strlen($item) != 0;
  });

  print_r($filtered);
?>

Output

PHP - Remove empty strings in array
ADVERTISEMENT

Conclusion

In this PHP Tutorial, we learned how to remove empty strings in an array, using PHP array_filter() function.