1$my_array = ['foo' => 1, 'hello' => 'world'];
2$allowed = ['foo', 'bar'];
3$filtered = array_filter(
4 $my_array,
5 function ($key) use ($allowed) {
6 return in_array($key, $allowed);
7 },
8 ARRAY_FILTER_USE_KEY
9);
1$numbers = [2, 4, 6, 8, 10];
2
3function MyFunction($number)
4{
5 return $number > 5;
6}
7
8$filteredArray = array_filter($numbers, "MyFunction");
9
10/**
11 * `$filteredArray` now contains: `[6, 8, 10]`
12 * NB: Use this to remove what you don't want in the array
13 * @see `array_map` when you want to alter/change elements
14 * in the array.
15 */
1
2<?php
3
4$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
5
6var_dump(array_filter($arr, function($k) {
7 return $k == 'b';
8}, ARRAY_FILTER_USE_KEY));
9
10var_dump(array_filter($arr, function($v, $k) {
11 return $k == 'b' || $v == 4;
12}, ARRAY_FILTER_USE_BOTH));
13?>
14
15
1$array = [1, 2, 3, 4, 5];
2
3$filtered = array_filter($array, function($item) {
4 return $item != 4; // Return (include) current item if expression is truthy
5});
6
7// $filtered = [1, 2, 3, 5]
1$numbers = [-2, 4, -6, 8, 10];
2
3function isPositive($number)
4{
5 return $number > 0;
6}
7
8$filteredArray = array_filter($numbers, "isPositive");
9
1PHP function array_filter(array $array, ?callable $callback, int $mode = 0) string[]
2--------------------------------------------------------------------------------
3Iterates over each value in the array passing them to the callback function.
4If the callback function returns true, the current value from array is returned into the result array.
5Array keys are preserved.
6
7Parameters:
8array--$array--The array to iterate over
9callable|null--$callback--[optional] The callback function to use If no callback is supplied, all entries of input equal to false (see converting to boolean) will be removed.
10int--$mode--[optional] Flag determining what arguments are sent to callback:
11ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value.
12ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value.
13
14Returns: the filtered array.