Problem with array_filter
This is a small trick to avoid issues when removing elements in PHP in an array.
If you have an array where some elements might be empty, like null, the first idea that comes to mind is doing something like this:
<?php
$array = ['a', null, 'b', 'c', null, 'd'];
array_filter($array, function($element) {
return !empty($element);
});
Of, if we don’t provide a callback to array_filter, PHP will do the same for us:
<?php
array_filter($array);
This will give us a new array with all the empty elements removed. The problem though, is that the structure of the array in terms of indexes is not the expected one:
<?php
$array = ['a', null, 'b', 'c', null, 'd'];
print_r(array_filter($array));
// Array
// (
// [0] => a
// [2] => b
// [3] => c
// [5] => d
// )
So the indexes for the items that we skipped are gone. This could be ok but when we try to use that array in some situations like a query in the DB, we might find some issues.
In MongoDB for example, if you’re trying to do a find with $in
, you’ll get an error if the array is missing some indexes.
Solution
The easiest solution to this problem of skipped indexes is to use array_values
:
<?php
$array = ['a', null, 'b', 'c', null, 'd'];
$result = array_values(array_filter($array));
print_r($result);
// Array
// (
// [0] => a
// [1] => b
// [2] => c
// [3] => d
// )
This will extract the values into a new, well indexed, array.