Current Location: Home> Function Categories> array_filter

array_filter

Use callback function to filter units in array
Name:array_filter
Category:Array
Programming Language:php
One-line Description:Use a callback function to filter elements in an array.

array_filter function

<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

parameter

  • array (required): The input array that needs to be filtered.
  • callback (optional): A callback function that handles each element in the array. If this parameter is not provided, all elements whose value is not false will be retained.
  • mode (optional): This parameter specifies the parameter of the callback function. 0 (default) means using array values as parameters of the callback function, and 1 means using array keys as parameters of the callback function.

Return value

Returns the filtered array. If there are no elements that meet the criteria, return an empty array.

Example


// 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>
Similar Functions
gitbox.net
Covering practical tips and function usage in major programming languages to help you master core skills and tackle development challenges with ease.
Repository for Learning Code - gitbox.net