Filtering an array

suggest change

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.

Filtering non-empty values

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); // keeps 1, 2, 3, 4, 5, 6, 7, and 8 at their original keys

Filtering by callback

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.

Filtering by index

Since PHP 5.6, a third argument chooses what the callback receives. ARRAY_FILTER_USE_KEY passes the key. ARRAY_FILTER_USE_BOTH passes the value and then the key. For example, to test indexes instead 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);

Indexes in filtered array

array_filter preserves the original keys. A common mistake is to walk the result with a for loop:

<?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
Warning: Undefined array key 1
2
Warning: Undefined array key 3
3
Warning: Undefined array key 5
4
Warning: Undefined array key 7
*/

The holes are the removed entries: index 1 was 0, 3 was null, 5 was '', and 7 was []. Before PHP 8 the diagnostic was Notice: Undefined offset.

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!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents