Using PHP's array_filter to Filter Array Elements with Callback Functions
This article explains PHP's array_filter function, describing its parameters, return value, and how it applies a user‑defined callback to each array element, with detailed code examples that demonstrate filtering for odd, even, and truthy values.
The array_filter function iterates over each value of an input array and passes it to a user‑defined callback. If the callback returns TRUE, the element is kept in the resulting array while preserving the original keys.
Signature :
array_filter(array $array, callable $callback = null, int $flag = 0)Parameters array – the array to be filtered. callback – the function that determines whether an element should be kept. If omitted, all entries that are equal to FALSE are removed. flag – optional flag that changes the arguments passed to the callback. Use ARRAY_FILTER_USE_KEY to receive only the key, or ARRAY_FILTER_USE_BOTH to receive both key and value.
Return value : the filtered array.
Example 1 – Filtering odd and even numbers
<?php
function odd($var) {
// returns whether the input integer is odd
return ($var & 1);
}
function even($var) {
// returns whether the input integer is even
return (!($var & 1));
}
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6,7,8,9,10,11,12);
echo "Odd :
";
print_r(array_filter($array1, "odd"));
echo "Even:
";
print_r(array_filter($array2, "even"));
?>Output:
Odd :
Array ( [a] => 1 [c] => 3 [e] => 5 )
Even:
Array ( [0] => 6 [2] => 8 [4] => 10 )Example 2 – Filtering truthy values (no callback)
<?php
$entry = array(0=>'foo', 1=>false, 2=>-1, 3=>null, 4=>'');
print_r(array_filter($entry));
?>Output:
Array ( [0] => foo [2] => -1 )Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
