The array_filter Function
The array_filter
function filters an array
using a given function. The function parameter
will sequentially receive the array elements,
and if the function returns
true
for an element, it remains in the array; if it returns
false
, it is removed. The array will contain only
those elements for which the function
returns true
.
If the original array is associative, its keys are preserved.
Syntax
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Example
Let's keep only the positive elements in the array:
<?php
function func($num)
{
if ($num >= 0) {
return true;
} else {
return false;
}
}
$arr = [1, -1, 2, -2, 3, -3];
$res = array_filter($arr, 'func');
var_dump($res);
?>
Code execution result:
[1, 2, 3]
Example
Let's shorten the condition:
<?php
function func($num)
{
return $num >= 0;
}
$arr = [1, -1, 2, -2, 3, -3];
$res = array_filter($arr, 'func');
var_dump($res);
?>
Code execution result:
[1, 2, 3]
Example
Let's rewrite it using an anonymous function:
<?php
$arr = [1, -1, 2, -2, 3, -3];
$res = array_filter($arr, function($num) {
return $num >= 0;
});
var_dump($res);
?>
Code execution result:
[1, 2, 3]
Example
Let's rewrite it using an arrow function:
<?php
$arr = [1, -1, 2, -2, 3, -3];
$res = array_filter($arr, fn($num) => $num >= 0);
var_dump($res);
?>
Code execution result:
[1, 2, 3]
See Also
-
the
array_map
function,
which applies a function to array elements -
the
array_walk
function,
which calls a function for array elements -
the
array_walk_recursive
function,
which recursively calls a function for array elements -
the
array_reduce
function,
which reduces an array