Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_filter()

Example

Filter an array’s values using a callback function.

<?php
function test_odd($var)
  {
  return($var & 1);
  }

$a1=array(1,3,2,3,4);
print_r(array_filter($a1,“test_odd”));
?>

Definition and Usage

The array_filter() function filters an array’s values based on a callback function.

It passes each value of the input array to the callback function; if the callback returns true, the current value is included in the result array. Array keys are preserved.

Syntax

array_filter(array, callbackfunction, flag)

Parameter Values

Parameter

Description

array

Required. Specifies the array to be filtered.

callbackfunction

Optional. Defines the callback function to be used.

flag

Optional. Defines the arguments sent to the callback:

  • ARRAY_FILTER_USE_KEY: Passes only the key as the argument to the callback (instead of the value).
  • ARRAY_FILTER_USE_BOTH: Passes both the value and the key as arguments to the callback (instead of just the value).

Technical Details

Return Value:

Returns the array with filtered values.

PHP Version:

4.0.6+

PHP Changelog:

PHP 5.6 introduced an optional flag parameter.