How to Remove Empty Array Elements in PHP
Very often, it is necessary to remove empty elements of the array in PHP. This snippet will provide you with the most common and efficient way to do it.
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 <kbd class="highlighted">array_filter</kbd> 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 <kbd class="highlighted">array_filter</kbd> works:
php array filter
<?php
$array = [0, 'amir', 'test', 490, null, '', 'Hello world'];
$array = array_filter($array);
var_dump($array);
?>Result
array(4) {
[1] =>
string(4) "amir"
[2] =>
string(4) "test"
[3] =>
int(490)
[6] =>
string(11) "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 <kbd class="highlighted">array_values</kbd> for re-indexing the array like this:
php array values
<?php
$array = [0, 'amir', 'test', 490, null, '', 'Hello world'];
$array = array_values(array_filter($array));
var_dump($array);
?>Result
array(4) {
[0] =>
string(4) "amir"
[1] =>
string(4) "test"
[2] =>
int(490)
[3] =>
string(11) "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 <kbd class="highlighted">array_filter</kbd> 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.