How to Remove Empty Array Elements in PHP

Frequently, some elements in an array can be empty, and it is necessary to remove them. In this short tutorial, we will provide you with the right function to do that.

The most common and correct way is to use the array_filter function. It will remove any element that is evaluated as FALSE (null, false, '', 0). By adding a callback function, you can customize the filter.

Here is how the array_filter works:

$array = [ 0, 'amir', 'test', 490, null, '', 'Hello world' ];
$array = array_filter($array);

Array
(
[1] => amir
[2] => test
[3] => 490
[6] => Hello world
)

In the example above, the value of $array is what is demonstrated below it in the brackets.

That operates properly but may leave index gaps inside an array. Luckily, you can fix it with the help of array-values for re-indexing the array like this:

$array = array_values($array);

Array
(
[0] => amir
[1] => test
[2] => 490
[3] => Hello world
)

In this example, as well, the value of $array is what is demonstrated below it in the brackets.

Describing the Array_filter Function

This function is capable of iterating over every value in the array and pass them to the callback function.

Once the callback function returns True, the current value from the array gets back into the result array.

The array_filter function has the following parameters: array, callback, and flag.

The first one is the array to iterate over. Callback is the callback function to apply. And, the flag specifies what arguments are forwarded to the callback.


Do you find this helpful?

Related articles