0
0
PHPprogramming~5 mins

Array filter function in PHP

Choose your learning style9 modes available
Introduction

The array filter function helps you pick only the items you want from a list. It makes your list smaller by keeping items that match a rule.

You have a list of numbers and want only the even ones.
You want to remove empty or null values from a list of strings.
You want to find all users older than 18 from a list of users.
You want to keep only the words that start with a certain letter.
Syntax
PHP
<?php
function array_filter(array $array, callable $callback): array
{
    $filteredArray = [];
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            $filteredArray[$key] = $value;
        }
    }
    return $filteredArray;
}
?>

The callback function decides if an item stays. It returns true to keep, false to remove.

The original keys are kept in the filtered array.

Examples
Filters only even numbers from the list.
PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$evenNumbers = array_filter($numbers, fn($num) => $num % 2 === 0);
print_r($evenNumbers);
Filtering an empty array returns an empty array.
PHP
<?php
$emptyArray = [];
$filteredEmpty = array_filter($emptyArray, fn($item) => $item > 0);
print_r($filteredEmpty);
Filtering a single-item array that matches the condition keeps that item.
PHP
<?php
$singleItem = [10];
$filteredSingle = array_filter($singleItem, fn($item) => $item > 5);
print_r($filteredSingle);
Filters words starting with 'a'.
PHP
<?php
$words = ['apple', 'banana', 'avocado'];
$filteredWords = array_filter($words, fn($word) => str_starts_with($word, 'a'));
print_r($filteredWords);
Sample Program

This program shows the original list of numbers, then filters to keep only even numbers, and prints the result.

PHP
<?php
// Original list of numbers
$numbers = [1, 2, 3, 4, 5, 6];

// Print original list
echo "Original numbers:\n";
print_r($numbers);

// Filter function to keep only even numbers
$evenNumbers = array_filter($numbers, function($number) {
    return $number % 2 === 0;
});

// Print filtered list
echo "\nFiltered even numbers:\n";
print_r($evenNumbers);
?>
OutputSuccess
Important Notes

Time complexity is O(n) because it checks each item once.

Space complexity is O(n) in the worst case if all items pass the filter.

Common mistake: forgetting the callback must return true or false.

Use array_filter when you want to keep items matching a condition. Use array_map if you want to change items instead.

Summary

array_filter keeps only items that match a rule you give.

The callback function returns true to keep an item, false to remove it.

It keeps the original keys of the array.