Custom Implementation of array_fill_keys Without Using PHP Array Functions

The array_fill_keys function in PHP is used to create an array by assigning a specified value to a list of keys. Below is a custom implementation of this functionality without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_fill_keys($keys, $value) {
    $result = [];

    // Loop through each key
    foreach ($keys as $key) {
        $result[$key] = $value; // Assign the value to the given key
    }

    return $result;
}

// Example usage
$keys = ['a', 'b', 'c', 'd'];
$value = "Hello";

$filledArray = custom_array_fill_keys($keys, $value);
print_r($filledArray);

Output:

Array
(
    [a] => Hello
    [b] => Hello
    [c] => Hello
    [d] => Hello
)

Explanation:

  1. Input Parameters:
    • $keys: An array of keys to be used in the new array.
    • $value: The value to assign to each key in the array.
  2. Result Initialization:
    • Create an empty $result array to hold the key-value pairs.
  3. Iteration:
    • Use a foreach loop to iterate over the $keys array.
    • For each key, add it to the $result array and assign it the specified $value.
  4. Output:
    • Return the $result array with keys mapped to the given value.

Keep Learning 🙂

Leave a Reply

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