English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP array_filter() Function Usage and Example

PHP Array Function Manual

array_filter — Filter array elements with a callback function

Syntax

array array_filter ( array $input [, callback $callback] );

Pass each value in the array to the callback function one by one. If the callback function returns true, the current value of the array will be included in the returned result array. The array keys remain unchanged.

Definition and usage

Traversal input Each value in the array, pass them to callback Function.

Parameter

Serial numberParameters and descriptions
1

input

Array to be traversed

2

callback

This callback function uses

Return value

It returns the filtered array.

Online Example

<?php
   function odd($var) {
      return($var & 1);
   }
   
   function even($var) {
      return(!($var & 1));
   }
   
   $input1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
   $input2 = array(6, 7, 8, 9, 10, 11, 12);
   
   echo "Odd values:\n";
   print_r(array_filter($input1, "odd");
   
   echo "Even values:\n";
   print_r(array_filter($input2, "even");
?>
Test and see ‹/›

Output results:

Odd values:
Array (
   [a] => 1
   [c] => 3
   [e] => 5 
)
Even values:
Array (
   [0] => 6 
   [2] => 8 
   [4] => 10 
   [6] => 12
)

PHP Array Function Manual