array_filter
Use callback function to filter units in array
<h2> Applicable to PHP version</h2>
<p>PHP 4.0.0 and above</p>
<h2>Function description</h2>
<p>The array_filter() function is used to filter elements in an array. It uses a callback function to process each element of the array, which returns a boolean value and filters elements based on the return value. If the callback function returns true, the element will be retained, otherwise it will be removed.</p>
<h2>Function Syntax</h2>
<pre>array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Returns the filtered array. If there are no elements that meet the criteria, return an empty array.
// Example 1: Filter out empty values in array
$array = [0, 1, 2, null, false, '', 3, 'hello'];
$result = array_filter($array);
print_r($result);
// Output:
// Array
// (
// [1] => 1
// [2] => 2
// [6] => 3
// [7] => hello
// )
// Example 2: Filtering with a custom callback function
$array = [1, 2, 3, 4, 5];
$result = array_filter($array, function($value) {
return $value % 2 == 0; // Only even numbers are retained
});
print_r($result);
// Output:
// Array
// (
// [1] => 2
// [3] => 4
// )
<h2>Description of sample code</h2>
<p>In the first example, the array_filter function is used to filter out all "false" values (such as 0, null, false, and empty strings). This example shows how to preserve only all valid array values.</p>
<p>In the second example, a custom callback function is used to filter out all elements that are not even numbers. This example demonstrates how to use callback functions to perform more complex filtering of array elements.</p>