How To Remove Empty Array Elements with PHP

In this tutorial we will learn How To Remove Empty Array Elements with PHP, We can use PHP array_filter() Function for this which filters the values of array and can also remove all empty values.

PHP array_filter() function

PHP array_filter() function filters the values of array using the callback function.

PHP array_filter() function passes each value of array one by one to the callback function and if the function returns true it will retain that value, otherwise that value will be filtered out by the function.

However, if the callback function is not defined the array_filter() function simply removes the empty array elements.

It removes all empty values, empty strings, NULL value, 0 as integer, 0 as string, false and empty array.

<?php
$array = array(0, "PHP", "", 200, NULL, "0", "-12",false,"Red");
$result = array_filter($array);                 
print_r($result);
?>

In above code, empty string (""), 0, "0", NULL and false are removed.

To avoid this from happening and to only remove empty values we can also make a custom callback functon with some conditions.

<?php
print_r(array_filter($array, fn($element) => !is_null($element) && $element !== ''));
?>

Demo

Notice that the values of resulting array has same keys as in the original array.

How To Remove Empty Array Elements with PHP How To Remove Common Values from two Arrays with PHP How To Find sum of array values with PHP How To Shuffle array Values in PHP How to Remove Duplicate Values from an array with PHP PHP Sort Associative array by Key PHP Sort Associative array by Value Sort array in numerical order with PHP Sort array in alphabetical order with PHP Sort array in descending order PHP Sort array in ascending order in PHP How to merge two or more arrays in PHP Add elements to the end of an array in PHP Add elements to the start of an array in PHP PHP Remove First Element from an Array PHP Remove Last Element from an Array Check if Key Exists in array PHP Check if Value exists in array PHP How to reverse an array in PHP PHP Print array line by line PHP Echo array values using foreach loop Count array values in PHP PHP Count How Many Times Word appears in String How to Reverse a String with PHP Check if Variable is Null in PHP