array filter function in php

In PHP, the array_filter() function is used to filter elements of an array based on a given callback function. It creates a new array containing only the elements for which the callback function returns true.

The syntax of array_filter() is as follows:

 
array_filter(array $array, callable $callback, int $flag = 0): array
 

Parameters:

  • $array: The input array that will be filtered.
  • $callback: A callback function that defines the filtering condition. It can be either a named function, an anonymous function (closure), or an array with an object method.
  • $flag (optional): An optional flag that determines how the callback function is applied to the array's elements. Possible values are:
    • ARRAY_FILTER_USE_KEY (1): Pass the array keys as the only argument to the callback, instead of the values.
    • ARRAY_FILTER_USE_BOTH (2): Pass both the array value and the key as arguments to the callback.

Return Value:

  • An array containing the elements for which the callback function returns true.

Here's an example of using array_filter() to filter an array of numbers, keeping only the even numbers:

In this example, the callback function checks if the value of each element is even (divisible by 2) and returns true for even numbers. The resulting array contains only the even numbers and their original keys.



 
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$filteredNumbers = array_filter($numbers, function ($value) {
    return $value % 2 === 0;
});

print_r($filteredNumbers);
Output:
 
Array(    [1] => 2    [3] => 4    [5] => 6    [7] => 8    [9] => 10)
 

Filter names starting with a specific letter:

The callback function checks if the first letter of each name matches the specified letter. Only "Charlie" satisfies the condition, so it is included in the filtered result.

$names = ["Alice", "Bob", "Charlie", "David", "Ella", "Frank"];

$letter = "C";

$filteredNames = array_filter($names, function ($name) use ($letter) {
    return stripos($name, $letter) === 0;
});

print_r($filteredNames);

Output: 
Array(    [2] => Charlie)
 

Filter out empty values from an array:

By not providing a callback function, array_filter() removes all elements with a "falsy" value (empty strings, null, false, 0).

$values = ["apple", "", "banana", null, "cherry", false, 0, "date"];

$filteredValues = array_filter($values);

print_r($filteredValues);

Output:
Array(    [0] => apple    [2] => banana    [4] => cherry    [7] => date)
 

Filter values based on a custom callback function:

Here, the callback function filters numbers greater than 5 and only even numbers.

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$filteredNumbers = array_filter($numbers, function ($num) {
    return $num > 5 && $num % 2 === 0;
});

print_r($filteredNumbers);

Output: 
Array(    [5] => 6    [7] => 8    [9] => 10)