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$var = [
2 'first' => 'one',
3 'second' => null,
4 'third' => 'three',
5];
6
7
8$filteredArray = array_filter($var);
9// output: ['first'=>'one,'third'=>'three']