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.
Table of Contents
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.