PHP Version
4.0.6+
// Array to filter
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Developer-defined callback function
function isEven($value) {
    return $value % 2 == 0; // Return true for even numbers
}

// Return a filtered array
$evenNumbers = array_filter($numbers, 'isEven');

print_r($evenNumbers);
/*
Output: The original array keys (indices) are preserved
Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)
*/
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
/**
 * Callback function
 *
 * @param mixed $element Each element of the array
 * @return bool Return true if the element meets the filtering condition, false otherwise
 *
 * Can be a named function (user-defined) or an anonymous function.
 */

// Using a named function as a callback
function callback($element) { // Define a named function
    // Filtering logic: return true for elements that should be included
}

array_filter($array, 'callback'); // Pass the name of the defined function as a string parameter

// Using an anonymous function as a callback
array_filter($array, function($element) {
    // Filtering logic: return true for elements that should be included
});
// Array to filter
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Developer-defined callback function
function isEven($value) {
    return $value % 2 == 0; // Return true for even numbers
}

// Return a filtered array
$evenNumbers = array_filter($numbers, 'isEven');

print_r($evenNumbers);
/*
Output: Original array keys (indices) are preserved
Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)
*/

// Important note: Accessing indices in the filtered array
var_dump($evenNumbers[0]); // null
$data = ['apple', '', 'banana', null, 'cherry'];

// Remove empty values
$filteredData = array_filter($data); // No callback provided

// Output result
print_r($filteredData);
$array = ["apple", "banana", "cat", "dog", "elephant"];

$stringsStartingWithA = array_filter($array, function ($string) {
    return $string[0] == "a";
});

print_r($stringsStartingWithA);
/*
Output:
Array
(
    [0] => apple
)
*/
$data = ['apple', '', 'banana', null, 'cherry'];

// Provide a callback function to remove empty values
$filteredData = array_filter($data, function ($value) {
    return !empty($value);
});

// Output result
print_r($filteredData);
/*
Output:
Array
(
    [0] => apple
    [2] => banana
    [4] => cherry
)
*/
$scores = [
    'Alice' => 85,
    'Bob' => 92,
    'Carol' => 78,
    'David' => 95
];

// Filter students with scores 90 or above
$topScorers = array_filter($scores, function ($value) {
    return $value >= 90;
});

// Output result
print_r($topScorers);
/*
Output:
Array
(
    [Bob] => 92
    [David] => 95
)
*/