Custom Implementation of array_filter Without Using PHP Array Functions

The array_filter function in PHP filters an array by using a callback function to determine whether an element should be included in the resulting array. Here’s how to implement this functionality manually without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_filter($array, $callback) {
    $result = [];

    // Loop through the array
    foreach ($array as $key => $value) {
        // Apply the callback function to check if the element should be included
        if (call_user_func($callback, $value, $key)) {
            $result[$key] = $value;
        }
    }

    return $result;
}

// Example usage
$inputArray = [1, 2, 3, 4, 5];
$callback = function ($value) {
    return $value % 2 === 0; // Filter even numbers
};

$filteredArray = custom_array_filter($inputArray, $callback);
print_r($filteredArray);
Array
(
    [1] => 2
    [3] => 4
)

Explanation:

  1. Input Parameters:
    • $array: The array to be filtered.
    • $callback: A user-defined function that takes two arguments ($value and $key) and returns true if the element should be included or false otherwise.
  2. Result Initialization:
    • Create an empty $result array to store the filtered elements.
  3. Iteration:
    • Use a foreach loop to iterate over the input $array.
    • For each element, call the $callback function with the current value and key.
    • If the callback returns true, add the key-value pair to the $result array.
  4. Output:
    • Return the $result array containing only the elements that passed the callback test.

Keep Learning 🙂

Leave a Reply

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