Custom Implementation of array_fill Without Using PHP Array Functions

The array_fill function in PHP is used to fill an array with a specific value, starting at a given index and for a specified number of elements. Below is a custom implementation of array_fill without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_fill($startIndex, $count, $value) {
    // Validate input
    if ($count <= 0) {
        return []; // Return an empty array for invalid count
    }

    $result = [];

    // Fill the array with the specified value
    for ($i = 0; $i < $count; $i++) {
        $result[$startIndex + $i] = $value;
    }

    return $result;
}

// Example usage
$startIndex = 3;
$count = 5;
$value = "Hello";

$filledArray = custom_array_fill($startIndex, $count, $value);
print_r($filledArray);
?>

Output:

Array
(
    [3] => Hello
    [4] => Hello
    [5] => Hello
    [6] => Hello
    [7] => Hello
)

Explanation:

  1. Input Parameters:
    • $startIndex: The index from where the array filling begins.
    • $count: The number of elements to fill.
    • $value: The value to fill the array with.
  2. Validation:
    • If $count is less than or equal to 0, return an empty array.
  3. Loop:
    • Use a for loop to iterate from 0 to $count – 1.
    • Add the $value to the $result array at index $startIndex + $i.
  4. Output:
    • Return the $result array with the specified values.

Keep Learning 🙂

Leave a Reply

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