PHP array_filter Example | array_filter() Function Tutorial
PHP array_filter() is an inbuilt function that filters the values of an array using a callback function. The array_filter() iterates over each value in an array passing them to the callback function. If the callback function returns a true value, the current value from an array is returned into the result array. Array keys are preserved.
PHP array_filter example
The array_filter() function filters the values of the array using the callback function.
The array_filter() function passes each value of an input array to the callback function. If the callback function returns a true value, then the current value from ant input is returned into the result array. Array keys are preserved.
Let’s take an example.
<?php // app.php function even($value) { return $value % 2 == 0; } $arr = [1, 2, 3, 4, 5]; print_r(array_filter($arr,"even"));
In the above code, we are checking every array item which is even, if it is odd then it will be filtered out from the array, and only even item stays in the array.
The output is following.
We can also write the array_filter() function like the following.
<?php // app.php $arr = [1, 2, 3, 4, 5]; $output = array_filter($arr, function($value) { return $value % 2 == 0; }); print_r($output);
The output will be the same as above; we have just written an anonymous function.
ARRAY_FILTER_USE_KEY
PHP 5.6 introduced the third parameter to array_filter() called flag, that you could set to ARRAY_FILTER_USE_KEY to filter by key instead of a value. See the following example.
<?php // app.php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; $outputA = array_filter($arr, function($k) { return $k == 'b'; }, ARRAY_FILTER_USE_KEY); print_r($outputA);
The output is following.
ARRAY_FILTER_USE_BOTH
You can set to ARRAY_FILTER_USE_BOTH to filter by key or value. See the following example.
<?php // app.php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; $outputB = array_filter($arr, function($v, $k) { return $k == 'b' || $v == 4; }, ARRAY_FILTER_USE_BOTH); print_r($outputB);
The output is following.
Accessing Keys in array_filter() function
You can access the current key of an array by passing a reference to the array into callback function and call key() and next() method in the callback function. See the following example.
<?php // app.php $data = array('first' => 1, 'second' => 2, 'third' => 3); $data = array_filter($data, function ($item) use (&$data) { echo "Filtering key ", key($data)."\n"; next($data); });
The output is following.
Finally, PHP array_filter Example | array_filter() Function Tutorial is tutorial.