PHP array_filter() Function

PHP array_filter() function is used to filter the elements of an array using a callback function(user-defined function).

If the callback function returns true, the current element is included in the result array. Array keys are preserved.

Syntax

array_filter($array, callbackfunction, flag)

Parameters

array(required): It specifies the array to filter

callbackfunction(optional): It evaluates each element.

flag(optional): Introduced in PHP 5.6 which determines what arguments are sent to the callback

  1. ARRAY_FILTER_USE_KEY: It passes the key as the only argument to callback function (instead of the value)
  2. ARRAY_FILTER_USE_BOTH: It passes both value and key as arguments to callback function (instead of the value)

Return value

It returns the filtered array.

Visual RepresentationVisual Representation of PHP array_filter() FunctionExample 1: How to Use PHP array_filter() function

<?php

function even($value)
{
   return $value % 2 == 0;
}

$arr = [11, 22, 33, 44, 55];

$resultArr = array_filter($arr,"even");

print_r($resultArr);

Output

Array
(
 [1] => 22
 [3] => 44
)

In this example, the output includes only the even numbers (22,44) from the $arr, which are filtered into the result array.

Example 2: ARRAY_FILTER_USE_KEYVisual Representation of ARRAY_FILTER_USE_KEY

<?php

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];

$resultArr = array_filter($arr, function($k) {
 return $k == 'b';
}, ARRAY_FILTER_USE_KEY);

print_r($resultArr);

Output

Array
(
 [b] => 2
)

Example 3: ARRAY_FILTER_USE_BOTHVisual Representation of ARRAY_FILTER_USE_BOTH

<?php

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];

$resultArr = array_filter($arr, function($v, $k) {
 return $k == 'b' || $v == 5;
}, ARRAY_FILTER_USE_BOTH);

print_r($resultArr);

Output

Array
(
 [b] => 2
 [e] => 5
)

Example 4: Accessing Keys

<?php

$arr = array('first' => 1, 'second' => 2, 'third' => 3);

$data = array_filter($arr, function ($item) use (&$arr) {
 echo "Filtering key ", key($arr)."\n";
 next($arr);
});

Output

Filtering key first
Filtering key second
Filtering key third

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.