In order to filter out values from an array and obtain a new array containing all the values that satisfy the filter condition, you can use the array_filter
function.
The simplest case of filtering is to remove all "empty" values:
$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$non_empties = array_filter($my_array); // $non_empties will contain [1,2,3,4,5,6,7,8];
This time we define our own filtering rule. Suppose we want to get only even numbers:
$my_array = [1,2,3,4,5,6,7,8];
$even_numbers = array_filter($my_array, function($number) {
return $number % 2 === 0;
});
The array_filter
function receives the array to be filtered as its first argument, and a callback defining the filter predicate as its second.
A third parameter can be provided to the array_filter
function, which allows to tweak which values are passed to the callback. This parameter can be set to either ARRAY_FILTER_USE_KEY
or ARRAY_FILTER_USE_BOTH
, which will result in the callback receiving the key instead of the value for each element in the array, or both value and key as its arguments. For example, if you want to deal with indexes istead of values:
$numbers = [16,3,5,8,1,4,6];
$even_indexed_numbers = array_filter($numbers, function($index) {
return $index % 2 === 0;
}, ARRAY_FILTER_USE_KEY);
Note that array_filter
preserves the original array keys. A common mistake would be to try an use for
loop over the filtered array:
<?php
$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$filtered = array_filter($my_array);
error_reporting(E_ALL); // show all errors and notices
// innocently looking "for" loop
for ($i = 0; $i < count($filtered); $i++) {
print $filtered[$i];
}
/*
Output:
1
Notice: Undefined offset: 1
2
Notice: Undefined offset: 3
3
Notice: Undefined offset: 5
4
Notice: Undefined offset: 7
*/
This happens because the values which were on positions 1 (there was 0
), 3 (null
), 5 (empty string ''
) and 7 (empty array []
) were removed along with their corresponding index keys.
If you need to loop through the result of a filter on an indexed array, you should first call array_values
on the result of array_filter
in order to create a new array with the correct indexes:
$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$filtered = array_filter($my_array);
$iterable = array_values($filtered);
error_reporting(E_ALL); // show all errors and notices
for ($i = 0; $i < count($iterable); $i++) {
print $iterable[$i];
}
// No warnings!