Home > Article > Backend Development > Filter arrays using PHP array_filter()
In PHP, the array_filter() function can help us quickly filter elements in an array. This article will introduce the usage of this function and related examples.
The basic syntax of the array_filter() function is:
array_filter(array $array [, callable $callback [, int $flag ]])
Among them, the $array parameter is the array to be filtered, the $callback parameter is an optional callback function, and the $flag parameter is an optional Selected flag that determines how callback function return values are handled.
Let’s explain these parameters one by one:
Let’s take a look at some examples:
$array = array('foo', false, -1, null, '', 0); $result = array_filter($array); print_r($result);
Output results:
Array ( [0] => foo [2] => -1 )
$array = array(1, 20, 3, 40, 5, 60, 7, 80, 9); $result = array_filter($array, function($value) { return $value > 10; }); print_r($result);
Output result:
Array ( [1] => 20 [3] => 40 [5] => 60 [7] => 80 )
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); $result = array_filter($array, function($value) { return $value % 2 == 0; }); print_r($result);
Output result:
Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
$array = array(0 => 'foo', 1 => 'bar', 2 => 'baz', 3 => 'qux'); $result = array_filter($array, function($value, $key) { return $key % 2 == 0; }, ARRAY_FILTER_USE_BOTH); print_r($result);
Output result:
Array ( [0] => foo [2] => baz )
To summarize, the array_filter() function is a very practical function that can help us quickly filter elements in the array and reduce the complexity and workload of the code. We can freely use callback functions to implement various filtering functions according to our own needs.
The above is the detailed content of Filter arrays using PHP array_filter(). For more information, please follow other related articles on the PHP Chinese website!