Home > Article > Backend Development > Introduction to PHP functions—array_filter(): Use callback functions to filter elements in an array
PHP function introduction—array_filter(): Use callback function to filter elements in the array
In PHP programming, array is a very common and important data type. As for array operations, one of the most common operations is to filter elements in the array. PHP provides a very practical function array_filter() to achieve this function.
The array_filter() function is to use the callback function to filter the array, retain the elements in the array that meet the conditions, and return a new array.
The array_filter() function is used as follows:
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
Parameter description:
Below we use several examples to demonstrate the use of the array_filter() function.
Example 1: Filter even numbers in the array
<?php // 原始数组 $arr = [1, 2, 3, 4, 5, 6]; // 过滤函数 function filter_even($value) { return ($value % 2 == 0); } // 使用array_filter()函数 $new_arr = array_filter($arr, 'filter_even'); // 输出结果 print_r($new_arr); ?>
Run the above code, the output result is:
Array ( [1] => 2 [3] => 4 [5] => 6 )
Example 2: Filter empty values in the associative array
<?php // 原始数组 $arr = ['name' => 'Tom', 'age' => '', 'gender' => 'male', 'email' => '']; // 过滤函数 function filter_empty($value) { return ($value !== ''); } // 使用array_filter()函数 $new_arr = array_filter($arr, 'filter_empty'); // 输出结果 print_r($new_arr); ?>
Run the above code, the output result is:
Array ( [name] => Tom [gender] => male )
The above two examples respectively show two cases of using the array_filter() function to filter elements in the array. In actual development, the array_filter() function has many other application scenarios, which we can use flexibly according to actual needs.
Summary:
The array_filter() function is a very commonly used and practical function in PHP. It provides a convenient way to filter elements in an array. By using callback functions to determine whether array elements meet conditions, we can implement various flexible filtering requirements. I hope the introduction in this article can help everyone and give everyone a deeper understanding of the use of the array_filter() function.
The above is the detailed content of Introduction to PHP functions—array_filter(): Use callback functions to filter elements in an array. For more information, please follow other related articles on the PHP Chinese website!