Filtering Array Elements with a Callback Function
Owner: SnippetBot
Created: 2026-08-09 00:00:16
Size: 0.81 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
// An array of numbers
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter to get only even numbers
$evenNumbers = array_filter($numbers, function($number) {
return $number % 2 == 0;
});
echo "Even Numbers:
";
print_r($evenNumbers);
// An array of strings
$fruits = ["apple", "banana", "orange", "grape", "kiwi"];
// Filter to get fruits with 'a' in their name
$fruitsWithA = array_filter($fruits, function($fruit) {
return strpos($fruit, 'a') !== false;
});
echo "
Fruits with 'a':
";
print_r($fruitsWithA);
// Filter with an associative array to remove empty values
$userData = [
"name" => "John Doe",
"email" => "john@example.com",
"phone" => null,
"address" => ""
];
$cleanedData = array_filter($userData);
echo "
Cleaned User Data (removed empty values):
";
print_r($cleanedData);
?>