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
- ARRAY_FILTER_USE_KEY: It passes the key as the only argument to callback function (instead of the value)
- 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 RepresentationExample 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_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_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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.