PHP array_filter() Function

The array_filter() function passes each value of a given array to a user defined function. If the user defined function allows, the current value from the array is returned into the result array.

Note: The function Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from the array is returned into the result array. Array keys are preserved.

ParameterDescription
arrayRequired. Specifies the array to filter
callbackfunctionOptional. Specifies the callback function to use
flagOptional. Specifies what arguments are sent to callback:ARRAY_FILTER_USE_KEY – pass key as the only argument to callback (instead of the value)ARRAY_FILTER_USE_BOTH – pass both value and key as arguments to callback (instead of the value)

Syntax

 array_filter(array,callbackfunction);

Example

function name($var)
{
	return($var & 2);
}
$array=array("Samuel","Cooper",5,6,7);
print_r(array_filter($array,"name"));

Output

Array ( [3] => 6 [4] => 7 ) 

Another Example

function name($var)
{
	return($var & 'Samuel');
}
$array=array("Samuel","Cooper",5,6,7);
print_r(array_filter($array,"name"));

Output

Array ( [0] => Samuel [1] => Cooper ) 

Leave a Reply

Your email address will not be published. Required fields are marked *