How to Build a Custom PHP Function for Applying a Callback to Arrays Without Built-In Functions

The array_map function in PHP applies a callback function to each element of an array and returns a new array with the transformed values. Below is a custom implementation of this functionality without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_map($callback, $array) {
    $result = []; // Initialize an empty array to store the transformed values

    // Loop through the array
    foreach ($array as $key => $value) {
        // Apply the callback function to each value and store the result
        $result[$key] = $callback($value);
    }

    return $result;
}

// Example usage
$array = [1, 2, 3, 4, 5];
$callback = function ($value) {
    return $value * 2; // Multiply each element by 2
};

$mappedArray = custom_array_map($callback, $array);
print_r($mappedArray);
?>

Output:

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Explanation:

  1. Input Parameters:
    • $callback: A callable function to be applied to each element.
    • $array: The input array whose elements will be processed.
  2. Result Initialization:
    • Create an empty $result array to store the transformed elements.
  3. Loop Through the Array:
    • Use a foreach loop to iterate over the input array.
    • For each element, apply the $callback function and store the result in $result with the same key.
  4. Return Value:
    • Return the $result array containing the transformed elements.

Keep Learning 🙂

Leave a Reply

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